java的未检查异常有哪些_Java中的已检查与未检查异常

检查异常

受检查的异常是在编译时发生的异常,这些也称为编译时异常。这些异常不能在编译时简单地忽略,程序员应注意(处理)这些异常。

例如,如果您在程序中使用FileReader类从文件中读取数据,如果在其构造函数中指定的文件不存在,则会发生FileNotFoundException,并且编译器会提示程序员处理该异常。

示例import java.io.File;

import java.io.FileReader;

public class FilenotFound_Demo {

public static void main(String args[]) {

File file = new File("E://file.txt");

FileReader fr = new FileReader(file);

}

}

如果您尝试编译上述程序,则会出现以下异常。

输出结果C:\>javac FilenotFound_Demo.java

FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown

FileReader fr = new FileReader(file);

^

1 error

注–由于FileReader类的方法read()和close()抛出IOException,因此可以观察到编译器与FileNotFoundException一起通知处理IOException。

未经检查的异常

未检查的异常是在执行时发生的异常。这些也称为运行时异常。其中包括编程错误,例如逻辑错误或API使用不当。编译时将忽略运行时异常。

例如,如果您在程序中声明了大小为5的数组,并尝试调用该数组的第6个元素,则会发生ArrayIndexOutOfBoundsExceptionexception。

示例public class Unchecked_Demo {

public static void main(String args[]) {

int num[] = {1, 2, 3, 4};

System.out.println(num[5]);

}

}

如果编译并执行上述程序,则会出现以下异常。

输出结果Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5

at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值