摘要: out.close(); //关闭输出流 out.write(end.getBytes()); //抛出IOException异常 }finally{ System.out.println(上一行代码:out.write(null)); //执行该行代码 } } (4)try只与catch语句块
out.close(); //关闭输出流
out.write("end".getBytes()); //抛出IOException异常
}finally{
System.out.println("上一行代码:out.write(null)"); //执行该行代码
}
}
(4)try只与catch语句块使用时,可以使用多个catch语句块来捕获try语句块中可能发生的多种异常。异常发生后,Java虚拟机会由上而下来检测当前catch语句块所捕获的异常是否与try语句块中发生的异常匹配,若匹配,则不再执行其他的catch语句块。如果多个catch语句块捕获的是同种类型的异常,则捕获子类异常的catch语句块要放在方法前面。
例如,下面代码演示捕获匹配的异常:
File file=new File("D:/myfile.txt");
try{
FileOutputStream out=new FileOutputStream(file);
out.write("start".getBytes());
out.close();
out.write("end".getBytes()); //抛出IOException异常
}catch(ArithmeticException e){
System.out.println("捕获到ArithmeticException异常");
}catch(IOException e){ //执行该catch语句块中的代码
System.out.println("捕获到IOException异常");
}
下面代码错误放置了捕获子类与父类的catch语句块的位置,最终导致编译错误:
File file=new File("D:/myfile.txt");
try{
FileOutputStream out=new FileOutputStream(file);
out.write("start".getBytes());
out.close();
out.write("end".getBytes()); //抛出IOException异常
}catch(Exception e){
System.out.println("捕获到父类Exception异常");
}catch(IOException e){ //编译出错,异常先被Exception的catch块捕获,该catch块永远不会执行
System.out.println("捕获到Exception的子类IOException异常");
}
(5)在try语句块中声明的变量,只在当前try语句块中有效,在其后的catch、finally语句块或其他位置都不能访问该变量。但在try-catch-finally语句块之外声明的变量,可以在try、catch或finally语句块中访问。例如:
int age1=0;
try{
age1=Integer.valueOf("20L"); //抛出NumberFormatException异常
int age2=Integer.valueOf("24L"); //抛出NumberFormatException异常
}catch(ArithmeticException e){
age1=-1; //编译成功
age2=0; //编译出错,无法解析age2
}finally{
System.out.println(age1); //编译成功
System.out.println(age2); //编译出错,无法解析age2
}
(6)对于发生的检查异常,必须使用try-catch语句捕获处理,或通过throws语句向上抛出,否则编译出错。
(7)在使用throw语句抛出一个异常对象时,该语句后面的代码将不会被执行,例如:
File file=new File("D:/myfile.txt");
try{
FileOutputStream out=new FileOutputStream(file);

RSS订阅





