throw vs throws throw
throw keyword is used to actually throw an exception object from a method or block of code.
throw new IOException("File not found");
throws
throws keyword is used in a method declaration to declare the exceptions that a method might throw.
void readFile() throws IOException, SQLException { }
| Aspect | throw | throws |
|---|---|---|
| Definition | Used to actually throw an exception object from a method or block of code. | Used in method declaration to declare the exceptions that a method might throw. |
| Usage Location | Inside a method or a block of code. | In method or constructor declaration only. |
| Number of Exceptions | Can throw only one exception object at a time. | Can declare multiple exceptions separated by commas. |
| Checked / Unchecked | Can throw both checked and unchecked exceptions. | Mainly for checked exceptions; can declare unchecked exceptions but not necessary. |
| Effect on Caller | Immediately transfers the exception to the caller. | Informs the caller that it should handle the declared exceptions. |
| Example | throw new IOException("File not found"); |
void readFile() throws IOException, SQLException { } |
| Requirement | Checked exceptions must be handled using try-catch or declared with throws. |
Caller must handle checked exceptions declared with throws. |
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weβre here to make our tutorials better based on your thoughts and suggestions.