ITeye博客

16.JAVA中的Exception

zzhblh · 2012-04-17 20:52 · Markdown

Java提供了两类主要的异常: runtime exception和checked exception。

所有的checked exception是从java.lang.Exception类衍生出来的, 而runtime exception则是从java.lang.RuntimeException或java.lang.Error类衍生出来的。

  • Runtime exceptions:   在定义方法时不需要声明会抛出runtime exception;   在调用这个方法时不需要捕获这个runtime exception;   runtime exception是从java.lang.RuntimeException或java.lang.Error类衍生出来的。

  • Checked exceptions:   定义方法时必须声明所有可能会抛出的checked exception;   在调用这个方法时,必须捕获它的checked exception,不然就得把它的exception传递下去;

throw 是手动抛出异常,throw new **Exception(); 抛出的是某一个异常类型的实例. throws 是方法抛出异常,写在方法声明处 public void show()throws **Exception,**Exception{} 紧跟throws后的是异常类型,而非异常实例,且可以声明抛出多个异常,同时这些异常类型大多都为 受检查异常类型。 throws 就是把异常抛出,就是逐级往上一级抛,但是在以后有个catch接受. Throws抛出异常交给调用该方法的方法 处理,即:

public class Test{
    public static void main(String[] args){
        Test2 test2 = new Test2();
        try{
           System.out.println("invoke the method begin!");
           test2.method();
           System.out.println("invoke the method end!");
        }catch(Exception e){
           System.out.println("catch Exception!");
        }
    }
}

class Test2{
    public void method() throws Exception{
        System.out.println("method begin!");
        int a = 10;
        int b = 0;
        int c = a/b;
        System.out.println("method end!");
    }
}

invoke the method begin!
method begin!
catch Exception!

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。