Thursday 24 May 2018

How to check an exception is checked or not?

Checked exceptions are the one that can be checked by compiler at the time of compilation.

When you see the exception hierarchy, it looks like below.



The classes Error, RuntimeException and their subclasses come under unchecked exception, whereas all other exception classes come under checked exception. So, if an exception is not subclass of either Error or RuntimeException can become a checked exception.

public static boolean isCheckedException(Throwable throwable) {
         return !(throwable instanceof RuntimeException || throwable instanceof Error);
}

Find the below working application.

Test.java
package com.sample.test;

import java.io.FileNotFoundException;

public class Test {

 public static boolean isCheckedException(Throwable throwable) {
  return !(throwable instanceof RuntimeException || throwable instanceof Error);
 }

 public static void main(String args[]) throws ClassNotFoundException {
  System.out.printf("Is 'ArrayIndexOutOfBoundsException' checked? %b\n",
    isCheckedException(new ArrayIndexOutOfBoundsException()));
  System.out.printf("Is 'FileNotFoundException' checked? %b\n", isCheckedException(new FileNotFoundException()));

 }
}

Output
Is 'ArrayIndexOutOfBoundsException' is checked false
Is 'FileNotFoundException' is checked true

No comments:

Post a Comment