InterviewSolution
| 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:
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 errorNow, 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) |
|||||||||||