1.

Checked Exception vs Unchecked Exception with examples

Answer»

The exceptions which are checked during compile time are called checked exceptions. When method throws checked exceptions, they must either be handled by the try-catch block or must declare the exception using the throws keyword. In case of violation, it will show a compile time error.

Unchecked exceptions are the exceptions that are not checked during compile time. If the code throws an unchecked exception and even if it is not handled, it will not generate a compile time error. This is dangerous as unchecked exceptions generally generate runtime errors. All unchecked exceptions are a child class of RuntimeException Class:

Checked ExceptionUnchecked Exception
Checked Exceptions are checked by the compiler.Unchecked exceptions are not checked by the compiler.
It is a subclass of Exception classIt is the subclass of RuntimeException class
They are required to be handled by the try catch block or be rethrown by a method using the throws keywordThey are not restricted
Checked Exceptions are GENERATED for errors that cannot be DIRECTLY prevented  from occuringUnchecked Exceptions are generated for errors that can be directly prevented from occuring

Example of a Checked Exception by reading a file which is not created:

import java.io.File; import java.io.FileReader; PUBLIC class Example {   public static void main(String args[])   {      File f = new File("D://abc.txt");      // file abc is not created, it generates a FileNotFoundException      FileReader obj= new FileReader(f);   } }

The exception generated is as follows

$javac Example.java Example.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown      FileReader obj= new FileReader(f);                      ^ 1 error

Now, let us see an example of an unchecked exception:

public class Example {   public static void main(String args[])   {      int val1=10;      int val2=0;      int ANS=val1/val2;      System.out.println(ans);   } }

The output is as follows:

$javac Example.java $java  Example Exception in thread "main" java.lang.ArithmeticException: / by zero at Example.main(Example.java:7)


Discussion

No Comment Found