温馨提示:这篇文章已超过239天没有更新,请注意相关的内容是否还可用!
Java异常类型是指在程序运行过程中可能出现的错误或异常情况。Java中的异常可以分为两类:Checked异常和Unchecked异常。Checked异常是在编译时检查的异常,必须在代码中进行处理或者声明抛出;Unchecked异常是在运行时检查的异常,不需要在代码中显式处理或者声明抛出。
示例代码如下:
// Checked异常示例
public class FileReadExample {
public static void main(String[] args) {
try {
FileReader fileReader = new FileReader("file.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line = bufferedReader.readLine();
System.out.println(line);
bufferedReader.close();
} catch (IOException e) {
System.out.println("文件读取出错:" + e.getMessage());
}
}
}
在上述代码中,我们尝试读取一个文件。由于文件可能不存在或者读取过程中发生错误,所以使用了`try-catch`语句块来捕获可能抛出的`IOException`异常。如果文件读取出错,将会输出异常信息。
// Unchecked异常示例
public class DivisionExample {
public static void main(String[] args) {
int a = 10;
int b = 0;
try {
int result = a / b;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("除数不能为0:" + e.getMessage());
}
}
}
在上述代码中,我们尝试进行除法运算,除数为0会抛出`ArithmeticException`异常。同样使用了`try-catch`语句块来捕获可能抛出的异常,并输出异常信息。
通过以上示例代码,我们可以看到,在处理Checked异常时,需要显式地使用`try-catch`语句块进行异常捕获;而对于Unchecked异常,可以选择是否进行异常捕获,如果不捕获,则异常会在程序运行时抛出。这种异常类型的划分可以帮助开发人员更好地处理程序中可能出现的错误情况,提高程序的稳定性和可靠性。