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("正常");
        }
    }
    
    
    
  • 相关阅读:
    Codeforces 691A Fashion in Berland
    HDU 5741 Helter Skelter
    HDU 5735 Born Slippy
    HDU 5739 Fantasia
    HDU 5738 Eureka
    HDU 5734 Acperience
    HDU 5742 It's All In The Mind
    POJ Euro Efficiency 1252
    AtCoder Beginner Contest 067 C
    AtCoder Beginner Contest 067 D
  • 原文地址:https://www.cnblogs.com/python-road/p/13220825.html
Copyright © 2011-2022 走看看