try{
//可能产生异常的语句
}catch{
......
}catch{
......
}finally{
......
}
上图左边,语句1发生异常,就会被捕获,跳转到相应的catch语句里,语句2并不会执行
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Test{
public static void main(String[] args) {
FileInputStream in = null;
try {
in = new FileInputStream("MyFile.txt");
int b;
b = in.read();
while(b != -1) {
System.out.println((char)b);
b = in.read();
}
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e) {
e.getMessage();
}finally {
try {
in.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
上述代码有一个细节要注意,如果将IOException和FileNotFoundException交换位置,编译时会报错,因为IOException包含FileNotFoundException,所以在IOException时已经捕获了异常,但是下面FileNotFoundException又会捕获一次异常,很不合理。<font color = red>捕获异常时,先捕获小的,再捕获大的,如果两个异常并列,顺序无所谓<font color = red>
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Test{
public static void main(String[] args) {
}
void m(int i) throws ArithmeticException{
if(i == 0)
throw new ArithmeticException("除数不能为0");
}
void f() throws IOException,FileNotFoundException{
FileInputStream in = null;
int b;
b = in.read();
while(b != -1) {
System.out.println((char)b);
b = in.read();
}
}
void f2() throws Exception {
f();
}
}
在当前函数抛出的异常,并不知道应该如何处理,就先将其抛出,由谁使用就由谁处理,如果使用者也不知道,就继续抛出 许多java库中的函数也有抛出异常,例如:
上述两个是java.io包中对文件进行操作的函数,他们自己本身就有异常要抛出,所以在使用的过程中要么catch,要么继续throws
class MyException extends Exception{
private int id;
public MyException(String message,int id){
super(message);
this.id = id;
}
public int getId(){
return id;
}
}
class A{
public void method() throws IOException{...}
}
class B1 extends A{
public void method() throws FileNotFoundException{...}//Error
}
class B2 extends A{
public void method() throws Exception{...}//Error
}
class B3 extends A{
public void method(){...}//Right
}
class B4 extends A{
public void method() throws IOException,MyException{...}//Error
}