zoukankan      html  css  js  c++  java
  • java 捕获与抛出异常

    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)
                 */
            }
        }
    }
    
    
  • 相关阅读:
    图说jdk1.8新特性(3)--- 注解与类型推测优化
    图说jdk1.8新特性(2)--- Lambda
    图说jdk1.8新特性(1)--- 函数式接口
    Linux应用与端口
    Linu如何查看磁盘占用情况及处理办法
    ThreadLocal剧集(一)
    缓存穿透、缓存击穿、缓存雪崩区别和解决方案
    MySQL 新建用户,为用户授权,指定用户访问数据库
    2019面试总结
    Java的设计模式
  • 原文地址:https://www.cnblogs.com/d534/p/15096888.html
Copyright © 2011-2022 走看看