异常处理

来源:互联网 发布:服务器监控软件免费 编辑:程序博客网 时间:2024/05/09 08:34

try-catch-finally语句

class MyException1 extends Exception{
 
}
class MyExcpetion2 extends Exception{

}

public class Exception{
 static void f1() throws MyException1{
  throw new MyException1();
 }
 static void f2() throws MyExcpetion2{
  throw new MyException2();
 }
 public static void main(String[] args){
  try{
   try{
    f1();
    f2();
   }
   catch(MMyExcpetion2 e2){
    System.out.println("处理异常2");
   }
   finally{
    System.out.println("第一个finally");
   }
  }
  catch(MyException1 e1){
   System.out.println("处理异常1");
  }
  finally{
   System.out.println("第二个finally");
  }
 }
}

 

程序运行结果:

第一个finally!

处理异常1

第二个finally!

无论如何,finally在没有默认时总要执行的。

 

声明抛出异常子句 : throws <用逗号分隔的异常列表>

抛出异常语句:throw <异常对象> ,异常对象必须是Throwable类或其子类的对象。

if (a<0) throw new MyException("异常1");

定义自己的异常类,必须是Throwable类的子类,通常是从Exception类或其子类的继承。

原创粉丝点击