捕获异常是通过三个关键词来实现的:try-catch-finally。用try来执行一段程序,如果出现异常,系统抛出一个异常,可以通过它的类型来捕捉(catch)并处理它,最后一步是通过finally语句为异常处理提供一个统一的出口,finally指定的代码都要被执行(catch语句可以有多条;finally语句最多只能有一条,根据自己的需要可有可无)。
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
* @author xiaofei 异常处理经典代码try-catch-finally
*/
public class Exception {
public static void main(String[] args) {
FileReader reader = null;
try {
// 读取E盘下的a.txt文件
reader = new FileReader("e:/a.txt");
char c = (char) reader.read();
System.out.println(c);
// 多个catch,子类在前,父类在后
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {// 关闭资源
try {
if (reader != null) {// 避免空指针异常
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}// main
}
import java.io.FileReader;
import java.io.IOException;
/**
* @author xiaofei 异常处理经典代码try-catch-finally
*/
public class Exception {
public static void main(String[] args) throws IOException {
FileReader reader = null;
// 读取E盘下的a.txt文件
reader = new FileReader("e:/a.txt");
char c = (char) reader.read();
System.out.println(c);
// 关闭资源
if (reader != null) {// 避免空指针异常
reader.close();
}
}// main
}
原文:https://www.cnblogs.com/zxfei/p/10745086.html