← Back to Chapters

Java throw & throws

? Java throw & throws

? Quick Overview

In Java, throw and throws are used to handle exceptions manually and declare possible exceptions. They help control error flow and make programs more reliable.

? Key Concepts

  • throw is used inside a method to explicitly throw an exception
  • throws is used in method signature to declare exceptions
  • throw creates an exception object
  • throws passes responsibility to the caller

? Syntax / Theory

throw: Used within method body.

throws: Used in method declaration.

? Code Example – Using throw

? View Code Example
// Demonstrates throwing an exception manually
public class ThrowExample {
    public static void main(String[] args) {
        int age = 15;
        if (age < 18) {
            throw new ArithmeticException("Not eligible to vote");
        }
        System.out.println("Eligible to vote");
    }
}

? Code Example – Using throws

? View Code Example
// Demonstrates declaring exception using throws
import java.io.*;

public class ThrowsExample {
    static void readFile() throws IOException {
        FileReader fr = new FileReader("data.txt");
        fr.close();
    }

    public static void main(String[] args) {
        try {
            readFile();
        } catch (IOException e) {
            System.out.println("File not found");
        }
    }
}

? Live Output / Explanation

In the first example, the program stops and throws an exception when age is less than 18. In the second example, the method declares a possible exception and the caller handles it using try-catch.

? Interactive Demo: Voting Logic

Simulate how the Java logic flows. Enter an age below to test the throw keyword behavior.

;
// Output will appear here...

? Tips & Best Practices

  • Use throw for custom validations
  • Use throws when method cannot handle exception
  • Prefer meaningful exception messages
  • Always handle checked exceptions properly

? Try It Yourself

  • Modify the age condition and observe behavior
  • Create a custom exception and throw it
  • Add multiple exceptions in throws clause