In a java programming, throws keyword list the type of exception that a method might throw.
In the throws clause, we declare all the exception that a method can throw.
Syntax:
1 2 | type method_name(parameter list) throws exception1, exception2 ….{ } |
Here, exception1, exception2 are comma, list of the exception that a method can throw.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class ExceptionClass { void demo() throws NullPointerException { // define throws System.out.println("Inside demo method."); throw new NullPointerException("demo"); } } public class ExceptionMain { public static void main(String args[]) { ExceptionClass ob = new ExceptionClass(); try { ob.demo(); // demo() definition comes within try block } catch (NullPointerException e) { System.out.println("Caught " + e); } } } |
1 2 | Inside demo method. Caught java.lang.NullPointerException: demo |
Explaination: We throws NullPointerException in the line “throw new NullPointerException(“demo”);” .
Here we set “demo” is a name of thread.
This line “throw new NullPointerException(“demo”);” throw the exception which is handled by catch block associated with try within main().