怕什么真理无穷

导航

关于try...catch和finally和throws的简单理解

public class Example24{
    public static void main(String[] args){
    try{
        int result=divide(4,0);//调用divide方法,用4除0,会报by zero的异常错误
        System.out.println(result);
    }catch(Exception e){//定义一个变量e,类型为Exception,异常专用类
        System.out.println("捕获的异常为:"+e.getMessage());//获取到异常并打印
        return;//有异常后,结束当前语句
    }finally{
        System.out.println("不管是否有异常,都会进入finally代码块");//不论是否有异常,都执行finally中的语句。如果catch中没有return,程序还能继续向下执行
    }
    System.out.println("程序继续向下执行……");
}

public static int divide(int x,int y){
    int result=x/y;
    return result;
}
}

public class Example25{
    public static void main(String[] args){
        try{
            int result=divide(4,0);//尽管4/2并不会报错,但由于调用的方法divide声明了此处可能会有异常,因此,也必须使用try...catch,否则编译不过
            System.out.println(result);
        }catch (Exception e){
            e.printStackTrace();//打印异常的固定写法。但本段没有对程序做任何处理,只是打印出来,因此如果当异常发生时,程序中终止运行
        }
    }
public static int divide(int x,int y) throws Exception{//在参数后,通过throws Exception声明此方法可能会有异常
    int result=x/y;
    return result;
    }
}

 

 

 

posted on 2021-02-27 21:17  惭愧书生  阅读(97)  评论(0编辑  收藏  举报