Java中常用的异常处理函数及其使用案例
发布时间:2023-10-11 15:27:17
在Java中,常用的异常处理函数有以下几种:try-catch、try-catch-finally、try-finally和throws。
1. try-catch语句是用来捕获并处理异常的,语法如下:
try {
// 可能会抛出异常的代码
} catch (ExceptionType1 exception1) {
// 处理ExceptionType1类型的异常
} catch (ExceptionType2 exception2) {
// 处理ExceptionType2类型的异常
} finally {
// 不管是否发生异常,都会执行的代码
}
使用案例:
try {
int result = 10 / 0; // 除数为0,会抛出ArithmeticException异常
} catch (ArithmeticException e) {
System.out.println("除数不能为0");
}
2. try-catch-finally语句在捕获并处理异常的同时,还会执行finally块中的代码,无论是否发生异常。语法如下:
try {
// 可能会抛出异常的代码
} catch (ExceptionType1 exception1) {
// 处理ExceptionType1类型的异常
} catch (ExceptionType2 exception2) {
// 处理ExceptionType2类型的异常
} finally {
// 不管是否发生异常,都会执行的代码
}
使用案例:
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream("file.txt");
// 读取文件内容
} catch (FileNotFoundException e) {
System.out.println("文件不存在");
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
System.out.println("文件关闭失败");
}
}
}
3. try-finally语句只有一个finally块,用于执行一些资源回收的操作,无论是否发生异常。语法如下:
try {
// 可能会抛出异常的代码
} finally {
// 不管是否发生异常,都会执行的代码
}
使用案例:
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream("file.txt");
// 写入文件内容
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
System.out.println("文件关闭失败");
}
}
}
4. throws语句用于将异常抛给调用者处理,可以在方法签名中声明可能抛出的异常。语法如下:
public void methodName() throws ExceptionType1, ExceptionType2, ... {
// 可能会抛出异常的代码
}
使用案例:
public void readFile() throws FileNotFoundException {
FileInputStream inputStream = new FileInputStream("file.txt");
// 读取文件内容
}
这些异常处理函数常用于Java程序中,可以根据实际情况选择合适的方式对异常进行处理,从而保证程序的可靠性和稳定性。
