In Java, throw
and throws
are both related to exceptions but serve different purposes:
throw
- The
throw
keyword is used to explicitly throw an exception in a method or block of code. - It is followed by an instance of an exception (e.g.,
new Exception()
). - We can use
throw
inside a method to indicate that something went wrong, and we want to signal that error to the caller.
Example
1 2 3 4 5 |
public void checkAge(int age) { if (age < 18) { throw new IllegalArgumentException("Age must be 18 or older"); } } |
throws
- The
throws
keyword is used in a method signature to declare that a method can throw one or more exceptions. It tells the compiler and the caller that this method might throw a particular exception, and it needs to be handled. throws
does not throw the exception itself, it just signals that the method could potentially throw it.
Example
1 2 3 |
public void readFile(String fileName) throws IOException { // Code that might throw an IOException } |
throw vs throws
Feature | throw | throws |
---|---|---|
Purpose | Used to explicitly throw an exception. | Used to declare exceptions a method can throw. |
Syntax | throw new Exception("Message"); |
public void method() throws Exception {} |
Where Used | Inside a method or block of code. | In the method signature. |
Function | Actually throws the exception. | Tells the compiler that an exception may be thrown, but doesn’t throw it itself. |
Control | Directly controls when an exception is thrown. | Indicates that the method might throw an exception. |
Example | throw new IllegalArgumentException("Invalid input"); |
public void readFile() throws IOException {} |