Java中异常处理的几种常见方式
在Java中,异常处理主要有以下几种常见方式:
try-catch
块:
这是最常用的异常处理方式。try
块包含可能会抛出异常的代码,如果发生异常,那么就会立即跳转到与其匹配的catch
块进行处理。
try {
// 可能会抛出异常的代码
int divByZero = 1 / 0;
} catch (ArithmeticException e) {
// 处理除以零的异常
System.out.println("Can't divide by zero!");
}
finally
块:finally
块总是会被执行,无论try-catch
块是否抛出异常。通常情况下,我们会将不需要在任何情况下都运行的代码放在这里。
import java.io.File;
try {
// 可能会抛出异常的代码
File file = new File("non_existent_file.txt");
System.out.println(file.exists() ? "File found!" : "File not found!"));
} catch (FileNotFoundException e) {
// 处理文件未找到的异常
System.out.println("File not found!");
}
throw
语句:
当需要主动抛出一个异常时,可以使用throw
语句。这通常发生在你无法恢复某个状态或者满足某些条件时。
public void divideByZero() {
try {
// 正常情况下不应该被调用的代码
int divResult = 1 / 0;
System.out.println("Div result: " + divResult);
} catch (ArithmeticException e) {
// 处理除以零的异常
throw new ArithmeticException("Can't divide by zero!");
}
}
以上就是Java中常见的异常处理方式。
还没有评论,来说两句吧...