In this post, we will see difference between checked and unchecked exception in java. It is important question regarding exceptional handling.
What is Exception?
Exception is unwanted situation or condition while execution of the program. If you do not handle exception correctly, it may cause program to terminate abnormally.
What is checked exception?
Checked exceptions are those exceptions which are checked at compile. If you do not handle them , you will get compilation error.
Lets understand with the help of example:
if you do not handle checked exception , you will get compilation error as below:
so there are two options two solve above compilation error.
Using try and catch block:
you can put error code prone in try block and catch the exception in catch block.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package org.arpit.java2blog; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class CheckedExceptionMain { public static void main(String args[]) { FileInputStream fis = null; try { fis = new FileInputStream("sample.txt"); int c; while ((c = fis.read()) != -1) { System.out.print((char) c); } fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package org.arpit.java2blog; import java.io.FileInputStream; import java.io.IOException; public class CheckedExceptionMain { public static void main(String args[]) throws IOException { FileInputStream fis = null; fis = new FileInputStream("sample.txt"); int k; while ((k = fis.read()) != -1) { System.out.print((char) k); } fis.close(); } } |
What is unchecked exception?
Example:
1 2 3 4 5 6 7 8 9 10 11 12 |
package org.arpit.java2blog; public class NullPointerExceptionExample { public static void main(String args[]){ String str=null; System.out.println(str.trim()); } } |
When you run above program, you will get below exception:
1 2 3 4 |
Exception in thread "main" java.lang.NullPointerException at org.arpit.java2blog.NullPointerExceptionExample.main(NullPointerExceptionExample.java:7) |
Another example:
1 2 3 4 5 6 7 8 9 10 11 12 |
package org.arpit.java2blog; public class ArrayIndexOutOfBoundExceptionExample { public static void main(String args[]){ String strArray[]={"Arpit","John","Martin"}; System.out.println(strArray[4]); } } |
When you run above program, you will get below exception:
1 2 3 4 |
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at org.arpit.java2blog.ArrayIndexOutOfBoundExceptionExample.main(ArrayIndexOutOfBoundExceptionExample.java:7) |
You can go through core java interview questions for beginners and experienced and Exception handling interview questions for more such questions.