Java基础-异常-throws Exception-抛声明

调用别人的程序方法,而别人的方法上声明了可能有异常
调用的地方须有两种处理方式中的一种(不然ecplise会提示语法错误):
1、也做异常声明,对异常不处理,收到异常我也向外抛----如果没有别的地方接收这个异常,那么异常被jvm接收,然后调用jvm默认的异常处理机制,中止程序
2、对异常进行 try—catch 预处理

1:做异常声明

public class ExceptionTest {
                                         //声明:对异常不处理,收到异常我也向外抛
public static void main(String[] args) throws Exception{
        DivDemo dd =new DivDemo();
        
        int resultD = dd.div(10, 0);
        System.out.println("resultD' value is :"+resultD);
        System.out.println("over!");
    }
}

class DivDemo{
    //在功能上通过throws的关键字--
    //--声明:调用该方法有可能会出现问题,可能向外抛异常
    public int div(int a,int b) throws Exception {
        
        return a/b;   
    }
}

:console:

“over!”没有被打印

image

 

2:try--catch处理

public class ExceptionTest {
    public static void main(String[] args){
        DivDemo dd =new DivDemo();
        
        int resultD;
        try {
            resultD = dd.div(10, 0);
            System.out.println("resultD' value is :"+resultD);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("over!");
    }
}

class DivDemo{
    //在功能上通过throws的关键字--
    //--声明调用该方法有可能会出现问题
    public int div(int a,int b) throws Exception {
        
        return a/b;   
    }
}

:console:

“over!” 打印,程序完成

image

posted @ 2015-07-14 14:44  cuiz_book  阅读(21230)  评论(0编辑  收藏  举报