Throw, throws, and finally

In Java, throw, throws, and finally are related to exception handling, but they have very different purposes.


1. throw

  • Purpose: Used inside a method to actually throw an exception object.
  • Syntax: throw new ExceptionType("message");
  • Key Points:
    • Works with a single exception instance at a time.
    • Control jumps immediately to the nearest matching catch block or to the caller if unhandled.
    • You can throw either checked or unchecked exceptions.

Example:

public void validateAge(int age) {
    if (age < 18) {
        throw new IllegalArgumentException("Age must be 18 or above");
    }
}

2. throws

  • Purpose: Declares that a method might throw certain exceptions, so callers must handle or rethrow them.
  • Syntax: returnType methodName(...) throws ExceptionType1, ExceptionType2 { // method code }
  • Key Points:
    • Goes in the method signature, not inside the method body.
    • Required for checked exceptions unless handled inside the method.
    • Multiple exception types can be declared (comma-separated).

Example:

public void readFile(String path) throws IOException {
    FileReader fr = new FileReader(path);
}

3. finally

  • Purpose: A block that always executes after try and catch, regardless of whether an exception occurred.
  • Syntax: try { // code that may throw exceptions } catch (Exception e) { // handle exception } finally { // cleanup code }
  • Key Points:
    • Used for cleanup (closing files, releasing resources).
    • Runs even if there’s a return in try or catch.
    • Does not run if the JVM shuts down abruptly (e.g., System.exit()).

Example:

try {
    FileReader fr = new FileReader("file.txt");
} catch (IOException e) {
    System.out.println("File not found");
} finally {
    System.out.println("This always runs");
}

Quick Comparison Table

KeywordWhere UsedMeaningExample
throwInside a methodActually throws an exception objectthrow new IOException();
throwsIn method declarationDeclares possible exceptions a method can throwvoid m() throws IOException
finallyAfter try/catch blockCode that always runs (for cleanup)finally { closeFile(); }

Leave a Reply