异常处理的两种典型代码
1、捕获异常(try-catch-finally)
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
* 异常处理的典型代码(捕获异常)
*/
public class Test7Trycatch {
public static void main(String[] args) {
FileReader reader = null;
try {
reader = new FileReader("H:/a.text");
char c1 = (char)reader.read();
char c2 = (char)reader.read();
System.out.println(""+c1+c2);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}finally {
try {
if (reader != null) {
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/*常用开发环境中,自动添加try-catch代码块的快捷键:
* 1、将所需处理的代码选中
* 2、IDEA:使用ctrl+alt+t
* 3、eclipse:使用alt+shift+z
* 4、ctrl+alt+o:优化导入的类和包
*/
2、声明异常抛出异常(throws)
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
*异常处理的典型代码(声明异常抛出throws)
*/
public class Test8Throws {
public static void main(String[] args) {
try {
readFile("joker.text");
} catch (FileNotFoundException e) {
System.out.println("所需文件不存在!");
} catch (IOException e){
System.out.println("所需文件读取错误!");
}
}
public static void readFile(String filename) throws FileNotFoundException,
IOException {
FileReader in = new FileReader(filename);
int tem = 0;
try {
tem = in.read();
while (tem != -1) {
System.out.println((char) tem);
}
} finally {
if (in != null) {
in.close();
}
}
}
}
注意:
方法重写中声明异常原则:子类重写父类方法时,如果父类方法有声明异常,那么子类声明的异常范围不可超过父类声明范围

本文详细介绍了Java编程中异常处理的两种常见方式:捕获异常(try-catch-finally)和声明异常抛出(throws)。通过实例展示了如何使用这两种机制来处理文件操作中的异常,并提到了代码快捷键。
17万+

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



