• 异常


    异常

    一.异常体系结构

    二.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("正常");
        }
    }
    
    
    
  • 相关阅读:
    Java之Map遍历方式性能分析:ketSet与entrySet
    Java之null保留字
    Java之&0xff用法解析以及原码、反码、补码相关知识
    Android之使用apt编写编译时注解
    Android之ViewPager.PageTransformer
    Android Studio利用javac导出Api文档
    06_Java多线程、线程间通信
    05_Java异常(Exception)
    04_Java面向对象特征之继承与多态
    03_Java面向对象特征: 封装性
  • 原文地址:https://www.cnblogs.com/python-road/p/13220825.html
Copyright © 2020-2023  润新知