Java抛出异常的代码分析
时间: 2024-06-21 21:03:43 浏览: 100
Java中抛出异常的代码通常可以分为两种情况:checked exception和unchecked exception。
checked exception是指在编译时就可以被检查出来的异常,必须在方法的声明中使用throws语句或者在方法内部使用try-catch语句进行处理。一般来说,如果一个方法可能抛出checked exception,那么它的调用者必须要捕获这个异常或者继续抛出它。
unchecked exception是指在运行时才会被检查出来的异常,不需要在方法的声明中使用throws语句或者在方法内部使用try-catch语句进行处理。一般来说,unchecked exception都是由程序员编写不够严谨的代码导致的,比如数组下标越界、空指针引用等。
下面是一个抛出checked exception的代码示例:
```
public class FileUtil {
public static void readFile(String fileName) throws IOException {
FileReader fr = null;
try {
fr = new FileReader(fileName);
// do something
} catch (FileNotFoundException e) {
// handle the exception
throw e;
} finally {
if (fr != null) {
fr.close();
}
}
}
}
```
下面是一个抛出unchecked exception的代码示例:
```
public class MathUtil {
public static int divide(int dividend, int divisor) {
return dividend / divisor;
}
}
```
阅读全文
相关推荐



















