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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值