一、Java异常基础介绍
关键字
try 需要监听的代码块,通过{}将可能出现异常的代码进行包裹
catch 异常类型,可能出现的异常类型,可以有多个,从上到下,对应异常的从小到大
finally 这里的语句不管异常是否出现,都会被执行(如果之前有renturn,则不会执行),常用于关闭连接
throw 在catch块中将异常向上抛出
throws 在方法定义中抛出异常
示例
public class Tets1 {
@Test
public void test1() throws IOException {
FileInputStream fileInputStream = null;
try {
File file = new File("D:\\test.txt");
fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[1024];
StringBuffer result = new StringBuffer();
while (true) {
int length = fileInputStream.read(buffer);
if (length > 0) {
result.append(new String(buffer));
} else {
break;
}
}
System.out.println(result);
} catch (IOException e) {
System.out.println(e.getMessage());
// 捕获异常之后,可以通过throw结合方法定义中的throws继续抛出异常
throw e;
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
fileInputStream.close();
} catch (Exception e) {
// 可以不做任何处理
}
}
}
}
二、Java异常类图
1、Throwable
Throwable是所有错误和异常的超类
有两个实现类Exception和Error
Exception是指程序本身可以处理的错误,与代码有关。
Error是指程序本身无法处理的错误,与代码没有关系,而是Java虚拟机出现的问题。
2、运行时异常(非受检异常)
运行时异常,是指在程序运行时出现的问题,该类型异常,编译器不会进行检查(估计也无法进行检查),所以又称为“非受检异常”。
常见的有:
NullPointerException(空指针异常)
ArrayIndexOutOfBoundException(数组下标越界异常)
ArithmeticException(除数为0异常)
3、非运行时异常(受检异常)
是除了RuntimeException以外的异常,在程序编译阶段就会进行检查的异常,如果不处理,程序就不能通过编译。
常见的有:
IOException(流传输异常)
SQLException(sql异常)