Have a Question?

If you have any question you can ask below or enter what you are looking for!

What is the checked and unchecked exception?

What are the checked and uncheched exception?
What is the checked and unchecked exception?

Fully checked v/s partially checked

  • A checked exception is said to be fully checked if and only if all its child classes also checked.
    • Example:- IOException, Interrupted Exception.
  • A checked exception is said to be partial checked if only if some of its child classes are unchecked.
    • Example:- Exception, Throwable.
  • Note:- The only possible partially checked exception in Java is Exception and Throwable.
  • CheckedException needs to be handled by the caller, Unchecked exception don’t. So, when you design your application you should take in mind what kind of exceptional situation you are managing.
  • UncheckedException:- NullPointerException, ArrayIndexOutofBound, IllegalArgumentException, ClassCastException, IllegalStateException, ConcurrentModificationException,
  • CheckedException:- FileNotFoundException, ParseException, ClassNotFoundException, CloneNotSupportException, SQLException
package com.java4us;

import java.io.FileWriter;
import java.io.IOException;

class Test {
    public static void main(String[] args) {
        Test test = new Test();
        String filePath = "hello.txt";
        String text = "Hello World";
        try {
            test.createFile(filePath, text);
        } catch (IOException ex) {
            System.err.println("Error creating file: " + ex);
        }
    }

    public void createFile(String path, String text) throws IOException {
        FileWriter writer = new FileWriter(path, true);
        writer.write(text);
        writer.close();
    }
}

In above program the method “createFile” will throw Checked exception “IOException then the caller of the method (main method) must handle that exception.

package com.java4us;

class Test {
    public static void main(String[] args) {
        Test test = new Test();
        String filePath = "hello.txt";
        String text = "Hello World";
        System.out.println(10 / 0); // Exception in thread "main" java.lang.ArithmeticException: divide by zero
    }
}

the above main method throwing an ArithmeticException but there is no try-catch block because of its unchecked exception.

Leave a Reply

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