方法调用过程因为参数传递错误,方法可能会抛出异常对象;用catch接收抛出的异常对象,使用如下方法输出有关异常的信息:
public String getmessage();
public void printDtackTrace();
public String toString();
try-catch-finally语句的综合应用TestException.java
public class TestException {
public static void test() {
int[] a =new int[2];
try {
int m=Integer.parseInt("1234");
int n=Integer.parseInt("abcde");//沿调用栈,逐层回溯,找catch
System.out.println(3/0);//在此之前抛出了异常,故try块自抛出异常,不再向下执行,ArithmeticException
a[2]=2;//NegativeArraySizeException
System.out.println("不会被执行!");
}
//catch(Exception e) {}//不能在使用Exception的子类之前使用Exception
catch(ArithmeticException e) {
e.printStackTrace();
}
catch(NegativeArraySizeException e) {//多个catch,当try中发生异常,会在紧跟的catch后顺序遍历对应的catch
e.printStackTrace();
}
finally {//catch后跟finally块儿,即使try-catch执行return,finally块儿仍被执行
System.out.println("finally部分1");//没有catch到异常,但此处可以被执行。
}
}
public static void main(String args[]) {
try{//此处若不处理NumberFormatException,则会将异常抛向JVM,处理效果与此处相同
test();
}
catch(NumberFormatException e) {//test函数并未对NumberFormatException做处理,故回溯到调用处进行处理
System.out.println(e.getMessage());//Exception.getMessage()可以输出错误的详细信息
//e.printStackTrace();//输出错误信息的另一种形式
}
finally {
System.out.println("finally部分2");
}
}
}
图:java ExceptionClass