Java throw and throws – Complete Guide with Examples
Learn the difference between throw and throws in Java, how to explicitly throw exceptions, declare exceptions in methods, and handle runtime and checked exceptions for robust programming.
throw and throws in Java – Complete Detailed Tutorial
Java provides throw and throws keywords to handle exceptions more effectively.
1. throw Keyword
- Used to explicitly throw an exception in Java
- Can throw checked or unchecked exceptions
- Syntax:
Key Points:
- Used inside a method
- Terminates the current method execution
- Can throw only one exception at a time
Example – Using throw:
Output:
2. throws Keyword
- Declares that a method may throw one or more exceptions
- Syntax:
Key Points:
- Used in method declaration
- Caller of the method must handle the exception
- Can declare multiple exceptions separated by comma
3. Example – Using throws
Output (if file not found):
4. Difference Between throw and throws
| Featurethrowthrows | ||
| Purpose | To explicitly throw an exception | To declare exceptions a method may throw |
| Usage | Inside method body | Method signature |
| Can throw | Single exception at a time | Multiple exceptions separated by comma |
| Termination | Immediately terminates method | Not terminates method, just declares |
| Example | throw new IOException(); | void read() throws IOException |
5. Example – throw vs throws
Output:
6. Key Points
- throw: explicitly throw an exception inside method
- throws: declare possible exceptions in method signature
- Checked exceptions: must be handled or declared
- Unchecked exceptions: optional to handle
- Enables controlled exception handling