Java Throws Keyword
As we know that Exceptions are divided into two parts.
1-Checked Exception
2-Unchecked Exception
1-Checked Exception:
"Checked Exception are those exceptions which are checked by the compiler at the compile time for the smooth execution of the program at run time.These exceptions happened mostly times so compiler aware to resolve the problem at compile time."
Example: FileNotFoundException, IOException, etc.
2-Unchecked Exception:
"Unchecked exceptions are those exceptions which are not checked by the compiler at the compile time for the smooth execution of the program at run time.These exceptions happened rarely times so compiler not aware to resolve the problem at compile time."
Example: NullPointerException,ArrayIndexOutOfBoundsException and ArithmeticException etc.
Lastly, come to the topic throws keyword handles only checked exceptions. Syntax structure for throws keyword
Demo example based on following above discussions
Case I: For checked exceptions
package com.navneet.javatutorial;
import java.io.FileNotFoundException;
import java.io.PrintWriter;public class ThrowsKeywordDemo {
public static void main(String[] args)throws FileNotFoundException {
PrintWriter pw=new PrintWriter("D:\ThrowsKeywordDemo.txt"); // checked Exception
pw.println("This is throws keyword demo");
pw.close();
System.out.println("The second statement");}
}
In the above program(checked Exception) the next statement executed because of the exception handled by throws keyword.
Case II: For Unchecked exceptions
package com.navneet.javatutorial;
import java.io.FileNotFoundException;
import java.io.PrintWriter;public class ThrowsKeywordDemo {
public static void main(String[] args)throws ArithmeticException{
String s;
System.out.println("The second statement");
System.out.println(10/0); // Unchecked Exception 1
System.out.println(s); // Unchecked Exception 2}
}
In the above program(Unchecked Exception) the next statement not executed because of the exception not handled by throws keyword.