手记

Java异常捕获的格式:try...catch...finally

Java异常捕获的格式:try...catch...finally

代码如下:专注代码块好几天:

class MyMath
{   //此时表示div()方法上如果出现了异常交给被调用处去处理
    public static int div(int x ,int y) throws Exception {
        int result = 0 ;
        System.out.println("***1、除法计算开始 ***") ;  //可以理解为把门打开
        try
        {
            result = x/y ;
        }
        catch (Exception e)
        {
            throw e ;  //继续抛异常
        }finally{
           System.out.println("***2、除法计算结束 ***") ;  //可以理解为把门关上
        }
        return result ;
    }
}

public class TestDemo
{
    public static void main(String args[]) {
        try
        {
             System.out.println(MyMath.div(10,0)) ;
        }
        catch (Exception e)
        {
            e.printStackTrace() ;
        }
    }
}

/*
对于以上给出的除法操作不可能永远都正常完成,所以应该进行一些合理的处理,首先如果说
某一个方法出现异常了,必须交给被调用处去处理,那么应该在方法上使用throws抛出。
*/

/*
如果以上代码出错之后,程序中的有些代码就不会执行了,这样明显不太对,经过修改之后,输出结果如下:
***1、除法计算开始 ***
***2、除法计算结束 ***
java.lang.ArithmeticException: / by zero
        at MyMath.div(TestDemo.java:8)
        at TestDemo.main(TestDemo.java:25)

*/

/*
这段代码理解一下,很重要:
    try
        {
            result = x/y ;
        }
        catch (Exception e)
        {
            throw e ;  //继续抛异常
        }finally{
           System.out.println("***2、除法计算结束 ***") ;  //可以理解为把门关上
        }
*/

/*
实际上以上的代码还可以缩写(把catch省略):
class MyMath
{   //此时表示div()方法上如果出现了异常交给被调用处去处理
    public static int div(int x ,int y) throws Exception {
        int result = 0 ;
        System.out.println("***1、除法计算开始 ***") ;  //可以理解为把门打开
        try
        {
            result = x/y ;
        }finally{
           System.out.println("***2、除法计算结束 ***") ;  //可以理解为把门关上
        }
        return result ;
    }
}

public class TestDemo
{
    public static void main(String args[]) {
        try
        {
             System.out.println(MyMath.div(10,0)) ;
        }
        catch (Exception e)
        {
            e.printStackTrace() ;
        }
    }
}

*/
/*
如果你直接使用了try...finally,那么表示你连处理一下的机会都没有,就直接给抛出了

*/

运行结果如下:

4人推荐
随时随地看视频
慕课网APP