Throws keyword

Whenever checked exception is thrown in program, either programmer has to handle it or he has to specify it. So that person going to use the code can gaurd his code from exception. For unchecked exception it's not mandatory, but checked exception is checked by compiler that it is handled or specified in code or not. If no then compilation is interrupted. throws keyword is used to specify which checked exception can be thrown in code.


Syntax:

	     throws <checked Exception> 

Program :


import java.io.*;
class file
{
public static void main(String arg[])
{
FileInputStream fis=new FileInputStream("one.txt");

}
}

If we try to execute above piece of code then it will show following error:

Error :

 two.java:10: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
FileInputStream fis=new FileInputStream("one.txt");
^
1 error


Reason for the error in above code is unhanding of checked exception. unreported exception FileNotFoundException; must be caught or declared to be thrown , specified in error as well that it must be caught or declared to be thrown. So now we will specify that main method can generate an exception using throws keyword.

Program :


import java.io.*;
class file
{
public static void main(String arg[]) throws FileNotFoundException
{
FileInputStream fis=new FileInputStream("one.txt");
}
}

Now compiler will allow compilation of above code. Throws keyword is used to specify what exception program can generate so that programmer who is going to use it, can handle it.

This program can generate "FileNotFoundException" which is checked exception. It means whether it must be handled or must be specified that main method can generate exception.