Difference between throw and throws?

☄️ throwUsed to actually throw an exception

What it does:

  • Used to manually trigger an exception.
  • Can only throw one exception at a time.
  • Typically used inside a method or block.

🔧 Syntax:

throw new ExceptionType(“Error message”);

🔍 Example:

class Demo {
    public static void validateAge(int age) {
        if (age < 18)
            throw new IllegalArgumentException("Age must be 18 or above");
        System.out.println("Access granted");
    }

    public static void main(String[] args) {
        validateAge(16);  // This will throw an exception
    }
}

🛡️ throws – Declares potential exception(s) a method might throw

✅ What it does:

  • Used in a method signature to declare that a method might throw one or more exceptions.
  • Used for checked exceptions, which must be handled or declared.

🔧 Syntax:

returnType methodName() throws Exception1, Exception2 { }

🔍 Example:

import java.io.*;

class Demo {
    public static void readFile(String path) throws IOException {
        FileReader file = new FileReader(path);
        // Reading logic...
    }

    public static void main(String[] args) throws IOException {
        readFile("nonexistent.txt");  // Might throw IOException
    }
}

🧠 Key Differences at a Glance

Featurethrowthrows
PurposeUsed to actually throw an exceptionDeclares possible exceptions
LocationInside method or blockIn method signature
Keyword Followed ByInstance of Throwable classException class name(s)
Throws How Many?One exception at a timeOne or more exception types
Checked or Unchecked?Works with both typesMostly used for checked exceptions
Causes Exception?Yes, actively throwsNo, just declares

Leave a Reply

Your email address will not be published. Required fields are marked *