最近将异常部分的基础知识进行了总结。
参见上图,欢迎拍砖
一:异常捕获和处理
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class KeyException{
public void method1() throws IOException {
FileInputStream fis = null;
try {
fis = new FileInputStream("");
fis.read();
//抛出异常后的语句
System.out.println("method1");
//多个catch,必须小范围的异常在前
} catch (FileNotFoundException e) {
//处理打开文件流可能出现异常
e.printStackTrace();
} catch (IOException e) {
//处理read方法可能抛出的异常
e.printStackTrace();
} finally {
if(fis != null) {
//这里如果出现异常,会将这个异常抛出给方法调用者
fis.close();
}
}
System.out.println("method1");
}
public void method2() throws FileNotFoundException {
File file = new File("d:\\test.txt");
if(!file.exists()) {
//相当于返回,后面语句不会执行
throw new FileNotFoundException("文件不存在"+file.getPath());
}
System.out.println("method2");
}
public static void main(String[] args) {
KeyException key = new KeyException();
try {
key.method1();
} catch (IOException e) {
//处理method1方法的异常
e.printStackTrace();
}
try {
key.method2();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
二:异常与重写
import java.io.FileNotFoundException;
import java.io.IOException;
public class OverRideException extends OverRide{
public void method1() {
System.out.println("子类method1方法");
}
public void method2() throws FileNotFoundException{
System.out.println("子类method2方法");
}
public static void main(String[] args) {
OverRide over = new OverRideException();
try {
over.method1();
over.method2();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class OverRide {
public void method1() throws IOException {
System.out.println(“父类类method1方法”);
}
public void method2() throws IOException{
System.out.println("父类method2方法");
}
}