x Java Java 8 JUnit JSON
  • XML
  • JDBC Spring Boot Microservices React Contact Us

    Checked and unchecked exception example

    Checked Exceptions

    Checked Exceptions are Exceptions which must be caught in the code using catch block or should be declared with throws clause. If not then the code would not compile. Checked Exceptions extend Exception class. Checked Exceptions are handled in scenarios when you are sure that application can recover from the situation that led to Exception.

    For example in below code when you create a FileReader instance, you need to provide catch block to catch the FileNotFoundException, else code will not compile or else the method can declare that it throws FileNotFoundException.

    public void readFile() {        
        try {
            FileReader reader = new FileReader("C://File.txt")
        } catch (FileNotFoundException e) { 
            e.printStackTrace(); 
        }
    }

    OR

    public void readFile() throws FileNotFoundException {        
        FileReader reader = new FileReader("C://File.txt")
    }

    Unchecked Exceptions

    Unchecked Exceptions (also called runtime exceptions) extend RuntimeException class which is not mandatory to be caught in the code using catch block nor required to be declared with throws clause.

    For example below code will throw ArithmeticException but it is not required to handle it, though you can still use try catch block to catch the Exception. Unchecked Exceptions are generally not caught as there is little you can do after an Unchecked Exception is thrown.

    public void divide() {        
        int div = 4/0;
    }
    public void divide() {        
        try {
            int div = 4/0;
        } catch (ArithmeticException e) { 
            e.printStackTrace(); 
        }
    }

    Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *











    Share This