Throw and Throws
- Eclipse: Oxygen
- Java: 1.8
Throw and Throws
Throws are used to suppress the error if the user doesn’t want to specify the try and catch block. Note that this doesn’t handle the error only suppresses it. It should be used only when the developer is sure that the error doesn’t occur.
The throw is used to forcefully throw an error where it is decided by the developer regarding certain conditions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class App { public static void main(String[] args) { try { someMethod(); } catch (FileNotFoundException e) { System.out.println("catch block of main method"); } } public static void someMethod() throws FileNotFoundException { System.out.println("Message from someMethod"); throw new FileNotFoundException(); } } |
Output
Message from someMethod
catch block of the main method
The keyword “throw” is used to throw an exception from any method or static block, while the keyword “throws”, used in a method declaration, indicates what exception can be thrown with this method. They are not interchangeable.
In a program, if there is a possibility that an exception occurs, the compiler always warns us and we must handle that checked exception. Otherwise, we will get a compile-time error.
To avoid this compile-time error, we can handle the exception in two ways:
- By using try-catch block
- By using throws keyword
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.io.FileNotFoundException; import java.io.FileReader; public class App { public static void main(String[] args) { someMethod(); } public static void someMethod() { try { FileReader in = new FileReader("file.txt"); } catch (FileNotFoundException e) { System.out.println("message from catch block"); } System.out.println("Message from someMethod"); } } |
Output
message from catch block
Message from someMethod
We can use the keyword throws to delegate the responsibility of handling exceptions to the caller, then the caller method is responsible for handling that exception.
1 2 3 4 5 6 7 8 9 |
public static void main(String[] args) throws FileNotFoundException { someMethod(); } public static void someMethod() throws FileNotFoundException { FileReader in = new FileReader("file.txt"); System.out.println("Message from someMethod"); } |
Output
Runtime error
Contributed by Poonam Tomar