java异常的分类Throwable
1.IO异常2.运行时异常3.Errow
java异常的捕捉
File file = new File("E:\\test\\test.exe");
这里new的只是一个pathname跟系统中是否存在该文件无关。路径也可以写成e:\test\test.exe。
try{
System.out.println("试图打开test.exe");
new FileInputStream(file);//读取本地文件中的字节数据
System.out.println("成功读取");
不存在的话会输出第一句,并在第二句事发现异常,随后进入捕捉异常区域
catch (FileNotFoundException e){//Exception e
if(e instanceof FileNotFoundException)
{System.out.println("文件不存在,请检查");
e.printStackTrace();//打印栈调用踪迹(分析用)
}
finally是一定会执行的区域
finally {
System.out.println("我是无论如何都会执行的");
}
throws 抛出异常对象,由调用该方法的方法去catch,主函数要是没catch住系统报错。eg:
public class TextException {
public static void main(String[] args) {
methed1();
}
public static void methed1() {
try { method2(); }
catch (FileNotFoundException e) { e.printStackTrace(); }
}
public static void method2() throws FileNotFoundException {
File file = new File("e:/test.test.exe");
FileInputStream fileInputStream = new FileInputStream(file);
System.out.println("成功打开"); }
}
该异常在method1中被catch不会再向上抛出