ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java 捕获与抛出异常

2021-08-03 23:35:30  阅读:179  来源: 互联网

标签:java 抛出 捕获 ArithmeticException System catch println public out


Test

package exception.demo02;

public class Test {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        try { //try 监控区域

            if (b == 0) { //throw  throws
                throw new ArithmeticException();//主动抛出异常
            }
            System.out.println(a / b);
            new Test().b();
//        } catch (ArithmeticException e) { //catch(想要捕获的异常类型) 捕获异常
//        } catch (Throwable e) {
//            System.out.println("程序异常");
        } catch (Error error) {
            System.out.println("error");
        } catch (Exception exception) {
            System.out.println("exception");
        } catch (Throwable throwable) {
            System.out.println("throwable");
        } finally { //finally 处理善后工作
            System.out.println("finally");
        }

//        要捕获多个异常,需从小到大去捕获;

//        System.out.println(a / b);//Exception in thread "main" java.lang.ArithmeticException: / by zero


        //调用test方法
        System.out.println( "----------调用test方法--------");
//        new  Test().test(1,0);
        

//        在方法上招聘的异常,需捕获,ctrl+alt+t
        System.out.println( "----------调用test方法 在方法上招聘的异常--------");
        try {
            new  Test().test(1,0);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        } finally {
        }
    }

    public void a() {
        b();
    }

    public void b() {
        a();
    }

//假设在这个方法中处理不了这个异常,可以在方法中抛出;
    public  void  test(int a,int b)throws  ArithmeticException{
        if (b == 0) { //throw  throws
            throw new ArithmeticException();//主动抛出异常,一般在方法中使用;
        }
        System.out.println(a / b);
    }

}

运行结果

Test2

package exception.demo02;

public class Test2 {
    public static void main(String[] args) {
        int a = 10;
        int b = 0;

//      选中内容;如:选中他“System.out.println(a / b);”  ctrl + alt + t =======>自动生成异常代码块

        try {
            System.out.println(a / b);
        } catch (Exception e) {
            System.exit(0); //结束程序
            e.printStackTrace();//打印错误的栈信息
            /*
            java.lang.ArithmeticException: / by zero
	at exception.demo02.Test2.main(Test2.java:11)
             */
        }
    }
}

标签:java,抛出,捕获,ArithmeticException,System,catch,println,public,out
来源: https://www.cnblogs.com/d534/p/15096888.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有