The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers fault that he is not performing check up before the code being used.
return_type method_name() throws exception_class_name{ //method code }
Now Checked Exception can be propagated (forwarded in call stack).
It provides information to the caller of the method about the exception.
Let's see the example of java throws clause which describes that checked exceptions can be propagated by throws keyword.
import java.io.IOException; class Testthrows1{ 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[]){ Testthrows1 obj=new Testthrows1(); obj.p(); System.out.println("normal flow..."); } }
There are two cases:
In case you handle the exception, the code will be executed fine whether exception occurs during the program or not.
import java.io.*; class M{ void method()throws IOException{ throw new IOException("device error"); } } public class Testthrows2{ public static void main(String args[]){ try{ M m=new M(); m.method(); }catch(Exception e){System.out.println("exception handled");} System.out.println("normal flow..."); } }
import java.io.*; class M{ void method()throws IOException{ System.out.println("device operation performed"); } } class Testthrows3{ public static void main(String args[])throws IOException{//declare exception M m=new M(); m.method(); System.out.println("normal flow..."); } }
import java.io.*; class M{ void method()throws IOException{ throw new IOException("device error"); } } class Testthrows4{ public static void main(String args[])throws IOException{//declare exception M m=new M(); m.method(); System.out.println("normal flow..."); } }