Java编程异常处理是一项重要的技术,用于捕获和处理在程序运行时可能发生的错误。Java提供了多种机制来处理异常,主要包括try-catch语句、try-catch-finally语句、try-with-resources语句以及自定义异常类。
使用 try-catch 语句,示例:
public class TryCatchExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // 引发 ArithmeticException
} catch (ArithmeticException e) {
System.out.println("捕获到异常: " + e.getMessage());
}
System.out.println("程序继续运行");
}
}
使用try-catch-finally语句,示例:
import java.io.FileReader;
import java.io.IOException;
public class TryCatchFinallyExample {
public static void main(String[] args) {
FileReader fileReader = null;
try {
fileReader = new FileReader("example.txt");
int data = fileReader.read();
while (data != -1) {
System.out.print((char) data);
data = fileReader.read();
}
} catch (IOException e) {
System.out.println("捕获到异常: " + e.getMessage());
} finally {
if (fileReader != null) {
try {
fileReader.close();
} catch (IOException ex) {
System.out.println("关闭文件时发生异常: " + ex.getMessage());
}
}
}
System.out.println("程序继续运行");
}
}
finally块代码,无论是否发生异常都会执行,常用于释放资源。

783

被折叠的 条评论
为什么被折叠?



