java学习笔记 异常处理

1、

public class ExceptionDemo1 {
    public static void main(String[] args) {
        System.out.println("1、除法计算开始:");
        try {
            int x = 10;
            int y = 0;
            System.out.println("开始计算:"+(x/y));
            System.out.println("除法结束");
        }catch (ArithmeticException e){
            e.printStackTrace();
        }finally {
            System.out.println("不管是否产生异常都执行");
        }
        System.out.println("**********");
    }
}

产生异常:

1、除法计算开始:
不管是否产生异常都执行
**********
java.lang.ArithmeticException: / by zero
    at com.hengqin.test1.ExceptionDemo1.main(ExceptionDemo1.java:9)

2、异常的处理流程

 

 3、throws关键字

class Math{
    //throws表示此方法中存在的异常由调用出处理
    public static int div(int x,int y)throws Exception{
        return x/y;
    }
}
public class ThrowsDemo1 {
    public static void main(String[] args) {
        System.out.println(Math.div(10,2));
    }
}

报错:

Error:(10, 36) java: 未报告的异常错误java.lang.Exception; 必须对其进行捕获或声明以便抛出
class Math{
    //throws表示此方法中存在的异常由调用出处理
    public static int div(int x,int y)throws Exception{
        return x/y;
    }
}
public class ThrowsDemo1 {
    public static void main(String[] args) {
        try {
            System.out.println(Math.div(10,2));
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

主方法上不要加上throws

4、throw关键字

手工抛异常

public class ThrowDemo1 {
    public static void main(String[] args) {
        try {
            throw new Exception("自己抛的异常");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
java.lang.Exception: 自己抛的异常
    at com.hengqin.test1.ThrowDemo1.main(ThrowDemo1.java:6)

5、异常处理标准格式

class Math{
    //throws表示此方法中存在的异常由调用出处理
    public static int div(int x,int y)throws Exception{
        int result = 0;
        try{
            System.out.println("***计算开始***");
            result = x/y;
        }catch (Exception e){
            throw e;  //继续抛出异常
        }finally {
            System.out.println("***计算结束***");
        }
        return result;
    }
}
public class ThrowsDemo1 {
    public static void main(String[] args) {
        try {
            System.out.println(Math.div(10,0));
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

 

posted @ 2020-06-24 15:25  橘子酱ing  阅读(182)  评论(0编辑  收藏  举报