Difference between checked and unchecked exception in java

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.

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.

package com.sheting.basic.exception.checked;

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();
        }
    }
}
Using throws :

You can use throws keyword to handle exceptions.

package com.sheting.basic.exception.checked;

import java.io.FileInputStream;
import java.io.IOException;

public class CheckedExceptionMain1 {

    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?

Unchecked exceptions are those exceptions which are not checked at compile time. Java won’t complain if you do not handle the exception.
Example:

package com.sheting.basic.exception.checked;

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:

Exception in thread "main" java.lang.NullPointerException
    at com.sheting.basic.exception.checked.NullPointerExceptionExample.main(NullPointerExceptionExample.java:8)

比如 ArrayIndexOutOfBoundsException 也是 unchecked exception.

猜你喜欢

转载自blog.csdn.net/tb9125256/article/details/81151750
今日推荐