Throws - Keyword:

Throws - Keyword:

The keyword throws is used to declare an exception from a method or constructor and defined with an instance of the Exception class.
It helps the programmer to predict that an exception may occur so it is better to write the exception handling code to maintain the normal flow of the code. There may be multiple exceptions written after the throws keyword.


return_type method_name() throws exception_class_name{  
//code block

checked exceptions:

To throw an unchecked exception from a method, it is not necessary to handle the exception or declare it in the throws clause.

Unchecked Exceptions:

To throw a checked exception using throw, we must either handle the exception in catch block or method explicitly and declare it using throws declaration.

Throw in java:

  • throw keyword is used to throw an exception explicitly from any method or constructor and is followed by an instance of the Exception class.


    throw Instance

Throws in java:

  • throws keyword is used in the method and constructor declaration and predicts which exception can be thrown by the method and is followed by exception class name.


    type methodName(parameters) throws exceptionList

Example :

Com.knowledge2life import; public class Main{ void m()throws IOException{ throw new IOException("device error");//checked exception } void n()throws IOException{ m(); } void p(){ try{ n(); }catch(Exception e){System.out.println("exception handled");} } public static void main(String args[]){ Main obj=new Main(); obj.p(); System.out.println("Knowledge2life"); } }


exception handled