zoukankan      html  css  js  c++  java
  • 异常

    异常

    一.异常体系结构

    二.Error和Exception的区别

    Error通常是灾难性的致命错误,是程序无法控制和处理的,当出现这些异常时,java虚拟机(jvm)一般会选择终止线程;
    Exception通常情况下是可以被程序处理的,并且在程序中应该尽可能的去处理这些异常。

    三.五个关键字

    try,catch,finally,throw,throws的使用

    public class Student {
        public static void main(String[] args) {
            try{
            new Student().test(1,0);
            }catch(ArithmeticException e){
                e.printStackTrace();
            }
          /* int a=1;
           int b=0;
           //假设要捕获多个异常,要从小到大捕获
           try{//try监控区域
               System.out.println(a/b);
           }catch(Exception e){//catch(想要捕获的异常类型)捕获异常
               System.out.println("这是一个零除错误!");
               e.printStackTrace();//打印错误的栈信息
           }finally{//处理善后工作
               System.out.println("你要重新设置一个除数");
           }
           */
    
    
        }
        //如果这个方法处理不了该异常,就向上抛出异常
    public void test(int a,int b) throws ArithmeticException{
            if (b==0){
                throw new ArithmeticException();//主动抛出异常,一般在方法中使用
            }
    }
    
    
    }
    
    

    三.自定义异常

    package oop;
    
    public class MyException extends Exception{
        private int detail;
        public MyException(int a){
            this.detail=a;
        }
    //打印出异常信息
        @Override
        public String toString() {
            return "MyException{" +
                    "detail=" + detail +
                    '}';
        }
    }
    
    

    使用自定义异常

    package oop;
    
    public class test {
        public static void main(String[] args) {
            try {
                test(10);
            }catch(MyException e){
                System.out.println("有异常");
                e.printStackTrace();
            }
        }
        public static void test(int a) throws MyException{
            if(a!=1){
                throw new MyException(a);
            }
            System.out.println("正常");
        }
    }
    
    
    
  • 相关阅读:
    容器基础(三): 使用Cgroups进行资源限制
    如何使用微软认知服务
    【PAT甲级】1004. Counting Leaves (30)
    PAT 1003. Emergency
    蓝桥杯2017模拟赛-风险度量
    HDU1242 Rescue
    HDU2437 Jerboas 深度优先遍历 + 剪枝
    HDU1257 最少拦截系统
    HDU1789 Doing Homework again
    UWP 打开、保存文件示例
  • 原文地址:https://www.cnblogs.com/python-road/p/13220825.html
Copyright © 2011-2022 走看看