对于检查型异常,Java强迫程序必须进行处理,处理的方式有以下两种:
1.声明抛出异常:不在当前方法内处理异常,而是把异常抛出到调用方法中;
2.捕获异常:使用try、catch和finally构成的语句块,捕获所发生的异常,进行相应的处理。
3.除了使用系统预定义的异常类外,用户还可以声明自己的异常类。
下面代码的输出是:
before call f2()
before call f3()
before call f4()
before call f5()
before
cn.edu.uibe.oop3.MyException: chu cuo la
at cn.edu.uibe.oop3.ExpDemo2.f5(ExpDemo2.java:36)
at cn.edu.uibe.oop3.ExpDemo2.f4(ExpDemo2.java:30)
at cn.edu.uibe.oop3.ExpDemo2.f3(ExpDemo2.java:25)
at cn.edu.uibe.oop3.ExpDemo2.f2(ExpDemo2.java:14)
at cn.edu.uibe.oop3.ExpDemo2.f1(ExpDemo2.java:8)
at cn.edu.uibe.oop3.ExpDemo2.main(ExpDemo2.java:46)
chu cuo la
Any Time
after call f3()
after call f2()
packagecn.edu.uibe.oop3;
classMyExceptionextendsException{
MyException(){
super("myexception");
}
MyException(String msg){
super(msg);
}
}
publicclassExpDemo2 {
publicvoidf1(intn){
System.out.println("before call f2()");
f2(n);
System.out.println("after call f2()");
}
publicvoidf2(intn){
System.out.println("before call f3()");
try{
f3(n);
}catch(MyException e){
e.printStackTrace();
System.out.println(e.getMessage());
}finally{
System.out.println("Any Time");
}
System.out.println("after call f3()");
}
publicvoidf3(intn)throwsMyException{
System.out.println("before call f4()");
f4(n);
System.out.println("after call f4()");
}
publicvoidf4(intn)throwsMyException{
System.out.println("before call f5()");
f5(n);
System.out.println("after call f5()");
}
publicvoidf5(intn)throwsMyException{
System.out.println("before");
if(n<0){
thrownewMyException("chu cuo la");
}else{
System.out.println("success!");
}
System.out.println("after");
}
publicstaticvoidmain(String[] args) {
ExpDemo2 ed =newExpDemo2();
ed.f1(-100);
}
}