Prerequisite: Throw and Throws in Java
The throw and throws are the concepts of exception handling in Java where the throw keyword throws the exception explicitly from a method or a block of code, whereas the throws keyword is used in the signature of the method.
The differences between throw and throws in Java are:
S. No. |
Key Difference |
throw |
throws |
---|---|---|---|
1. | Point of Usage | The throw keyword is used inside a function. It is used when it is required to throw an Exception logically. | The throws keyword is used in the function signature. It is used when the function has some statements that can lead to exceptions. |
2. | Exceptions Thrown | The throw keyword is used to throw an exception explicitly. It can throw only one exception at a time. | The throws keyword can be used to declare multiple exceptions, separated by a comma. Whichever exception occurs, if matched with the declared ones, is thrown automatically then. |
3. | Syntax | Syntax of throw keyword includes the instance of the Exception to be thrown. Syntax wise throw keyword is followed by the instance variable. | Syntax of throws keyword includes the class names of the Exceptions to be thrown. Syntax wise throws keyword is followed by exception class names. |
4. | Propagation of Exceptions | throw keyword cannot propagate checked exceptions. It is only used to propagate the unchecked Exceptions that are not checked using the throws keyword. | throws keyword is used to propagate the checked Exceptions only. |
Examples
1. Java throw
Java
// Java program to demonstrate the working // of throw keyword in exception handling public class GFG { public static void main(String[] args) { // Use of unchecked Exception try { // double x=3/0; throw new ArithmeticException(); } catch (ArithmeticException e) { e.printStackTrace(); } } } |
Output:
java.lang.ArithmeticException at GFG.main(GFG.java:10)
2. Java throws
Java
// Java program to demonstrate the working // of throws keyword in exception handling import java.io.*; import java.util.*; public class GFG { public static void writeToFile() throws Exception { BufferedWriter bw = new BufferedWriter( new FileWriter( "myFile.txt" )); bw.write( "Test" ); bw.close(); } public static void main(String[] args) throws Exception { try { writeToFile(); } catch (Exception e) { e.printStackTrace(); } } } |
Output:
java.security.AccessControlException: access denied ("java.io.FilePermission" "myFile.txt" "write") at GFG.writeToFile(GFG.java:10)