Difference Between throw and throws in Java
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.
1. Java throw
java.lang.ArithmeticException at GFG.main(GFG.java:10)
2. Java throws
java.security.AccessControlException: access denied ("java.io.FilePermission" "myFile.txt" "write") at GFG.writeToFile(GFG.java:10)
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.