什么是异常:导致程序的正常流程被中断的事件,叫做异常。
Java中通过 new FileInputStream(f) 试图打开某文件,就有可能抛出文件不存在异常FileNotFoundException
package exception;
import java.io.File;
import java.io.FileInputStream;
public class TestException {
public static void main(String[] args) {
File f= new File("d:/WZ.exe");
//试图打开文件WZ.exe,会抛出FileNotFoundException,如果不处理该异常,就会有编译错误
new FileInputStream(f);
}
}
处理异常的手段:
1.try catch finally(捕捉异常,自己消化掉)
2.throws(把锅甩给上一层方法调用者,让它处理)
例1:
package exception;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class TestException {
public static void main(String[] args) {
File f= new File("d:/WZ.exe");
try{
System.out.println("试图打开 d:/WZ.exe");
new FileInputStream(f);
System.out.println("成功打开");
}
catch(FileNotFoundException e){
System.out.println("d:/WZ.exe不存在");
e.printStackTrace();
}
finally{
System.out.println("无论文件是否存在, 都会执行的代码");
}
}
}
例2:
package exception;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class TestException {
public static void main(String[] args) {
method1();
}
private static void method1() {
try {
method2();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void method2() throws FileNotFoundException {
File f = new File("d:/WZ.exe");
System.out.println("试图打开 d:/WZ.exe");
new FileInputStream(f);
System.out.println("成功打开");
}
}
throws与throw这两个关键字接近,不过意义不一样,有如下区别:
1. throws 出现在方法声明上,而throw通常都出现在方法体内。
2. throws 表示出现异常的一种可能性,并不一定会发生这些异常;throw则是抛出了异常,执行throw则一定抛出了某个异常对象。