Throws and throw both are keywords in java, used for handling the exception. When a method is not able to handle the checked exception, it should declared with throws keyword. Throws can be declared with multiple Exceptions separated with comma. Throw is used within the method to throw exception to the caller.
Difference between throw and throws in java.
- Throws and throw both are keywords in java, used for handling the exception. When a method is not able to handle the checked exception, it should declared with throws keyword. Throws can be declared with multiple Exceptions separated with comma. Throw is used within the method to throw exception to the caller.
public void example()throws IOException { throw new IOException("Hello"); }
static { try { throw new Exception("Exception"); catch(Exception e){} } }
Using throw statement::
- Throw clause transfer the control to nearest catch block, if the catch block is not there program will terminate.
- Throw statement can terminate the program.
Using Throws statement:
- Throws statement is used by method to specify the type of exception it throws. If the method is able to raise an exception but it cannot be handle, It must specify that it will handled by calling method.
Example: A simple program using throw and throws .
public class Demo { public void demomethod()throws ClassNotFoundException { System.out.println("in method"); throw new ClassNotFoundException(); } public static void main(String args[]) { try { Demo ob=new Demo(); ob.demomethod(); } catch(ClassNotFoundException e) { System.out.println("caught-"+e); } } }Output: After compiling and executing the above program. output will be as follows.