36异常的基本常识

1.异常的分类

1.Throwable(异常根类)
Error产生的异常:虚拟机错误、内存溢出、线程死锁
Excepetion:程序本身可以处理的异常。异常处理通常针对这种类型异常的处理

非检查异常 Unchecked Exception:空指针异常、数组下标越界异常、算数异常、类型转换异常; (是可以不检查的)
检查异常 Checked Exception:(系统要求必须检查)

异常

2.异常处理


异常处理

3.try...catch...final

package com.imooc.test;

import java.util.InputMismatchException;
import java.util.Scanner;

public class TryDemoOne {

    public static void main(String[] args) {
    /*  // 要求:定义两个整数,输出两数之商
        
        int one=12;
        int two=2;
        System.out.println("one和two的商是:"+ (one/two));
    */
        
        // 要求:定义两个整数,接受用户的键盘输入,输出两数之商
        Scanner input=new Scanner(System.in);
        System.out.println("=====运算开始=====");
        try{
            System.out.print("请输入第一个整数:");
            int one=input.nextInt();
            System.out.print("请输入第二个整数:");
            int two=input.nextInt();
            System.out.println("one和two的商是:"+ (one/two));
        }catch(ArithmeticException e){
            System.exit(1);//终止程序运行 可以通过Java API 查看具体的用法https://docs.oracle.com/javase/8/docs/api/ Java.lang包下的system类的方法
            System.out.println("除数不允许为零");
            e.printStackTrace();
        }catch(InputMismatchException e){
            System.out.println("请输入整数");
            e.printStackTrace();
        }catch(Exception e){//一般用在最后一个catch,在前面的类型没有检查出来,用这个进行包含
            System.out.println("出错啦~~");
            e.printStackTrace();
        }finally{//无论是否发生异常,总会执行这个
            System.out.println("=====运算结束=====");
        }
    }

}

4.catch 中的 return

package com.imooc.test;

import java.util.InputMismatchException;
import java.util.Scanner;

public class TryDemoTwo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int result=test();
        System.out.println("one和two的商是:"+ result);
        
    }

    public static int test(){
        Scanner input=new Scanner(System.in);
        System.out.println("=====运算开始=====");
        try{
            System.out.print("请输入第一个整数:");
            int one=input.nextInt();
            System.out.print("请输入第二个整数:");
            int two=input.nextInt();
            return one/two;
        }catch(ArithmeticException e){
            System.out.println("除数不允许为零");
            return 0;
        }finally{
            System.out.println("=====运算结束=====");
        //  return -100000;//无论上面进入哪个catch,内部的return都会失效,最后由finally中的return返回
        }
    }
}

5throws
通过throws声明将要抛出何种类型的异常,通过throw将产生的异常抛出

1.public static int test() throws Exception 在函数后面声明可能产生的异常。
2.throws后面接多个异常类型,中间用逗号分隔

  1. RuntimeException都是UncheckedException非检查型异常。当throws非检查型异常时,在调用方法处,编译器不会要求对异常进行处理。这里的ArithmeticException 和 InputMismatchException就是非检查型异常,就算你不去try,编译器也不会报错。如果需要提醒检查,可以通过加文档注释的方法,提醒
    4.Exception类型属于检查型异常,编译器会进行错误提示必须处理,即必须try...catch

可能直接使用一个Exception,然后在后面再对抛出的类进行细分

    public static int test() throws Exception {
        Scanner input = new Scanner(System.in);
        int one = input.nextInt();
        int two = input.nextInt();
        return one/two; 
    }

    

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
             System.out.println(test());
        } catch (ArithmeticException e) {
            System.out.println("被除数不能为0");
            e.printStackTrace();
        } catch(InputMismatchException e) {
            System.out.println("数字格式错误,请输入一个整数");
            e.printStackTrace();
        } catch(Exception e) {
            
        }
        
    }

也可以直接throws的后面就接上可能抛出的具体异常子类


    public static int test() throws ArithmeticException,InputMismatchException {
        Scanner input = new Scanner(System.in);
        int one = input.nextInt();
        int two = input.nextInt();
        return one/two; 
    }

    
      /**
     * 测试接收数据相除结果的方法
     * @return 两个接收数据的商
     * @throws ArithmeticException
     * @throws InputMismatchException
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
             System.out.println(test());
        } catch (ArithmeticException e) {
            System.out.println("被除数不能为0");
            e.printStackTrace();
        } catch(InputMismatchException e) {
            System.out.println("数字格式错误,请输入一个整数");
            e.printStackTrace();
        } 
        
    }

6 通过throw 主动抛出异常,进行一些业务逻辑实现
* throw 抛出异常对象的处理方案
* 1.通过try...catch 包含throw语句--自己抛出自己处理,
* 2.通过throws在方法声明出抛出异常类型--谁调用谁处理--调用者可以自己处
理,也可以继续往上抛,throws后面接的异常类与throw对象相同的类型或者其父类。
throws Exception 可以换成 throws Throwable,但不可以换成子类

package com.imooc.test;

import java.util.Scanner;

public class TryDemoFour {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //testAge1();
        try {
            testAge2();
        } catch (Exception e) {
            
            e.printStackTrace();
        }
    }
    /**
     * throw 抛出异常对象的处理方案
     * 1.通过try...catch 包含throw语句--自己抛出自己处理
     * 2.通过throws在方法声明出抛出异常类型--谁调用谁处理--调用者可以自己处理,也可以继续往上抛
     * @throws Exception 
     */
    //描述酒店的入住规则:限定年龄,18岁以下,80岁以上的住客必须由亲友陪同
    public static void testAge1() {
        try {
            System.out.println("请输入年龄:");
            Scanner input = new Scanner(System.in);
            int age = input.nextInt();
            if(age<18 || age>80) {
                throw new Exception("18岁以下,80岁以上的住客必须由亲友陪同");//Exception有有一个构造函数,可以传入字符串
            } else {
                System.out.println("欢迎光临");
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
        
    }
    
    public static void testAge2() throws Exception {
    
        System.out.println("请输入年龄:");
        Scanner input = new Scanner(System.in);
        int age = input.nextInt();
        if(age<18 || age>80) {
            throw new Exception("18岁以下,80岁以上的住客必须由亲友陪同");//Exception有有一个构造函数,可以传入字符串
        } else {
            System.out.println("欢迎光临");
        }
    
    }
    
}

7.自定义异常
自定义一个类继承Exception 即可,这个类的用法与其他的完全相同

package com.imooc.test;

public class HotelException extends Exception {
    
    public HotelException() {
        super("18岁以下,80岁以上的住客必须由亲友陪同");//使用Exception 进行构造函数参数的传递
    }
    @Override
    public String getMessage() {//这个函数可以获取传入构造函数的参数
        // TODO Auto-generated method stub
        return super.getMessage();
    }
}

8 异常链

1.只有最后一个异常抛出来了。

package com.imooc.test;

public class TryDemoFive {

    public static void main(String[] args) {
        try {
            test3();
        } catch (Exception e) {
            
            e.printStackTrace();
        }

    }
    public static void test1() throws Exception {
        throw new Exception("test1异常");
    }
    
    public static void test2() throws Exception {
        try {
            test1();
        } catch (Exception e) {
            throw new Exception("test2异常");
        }
    }
    public static void test3() throws Exception {
        try {
            test2();
        } catch (Exception e) {
            throw new Exception("test3异常");
        }
    }

}

输出结果:
java.lang.Exception: test3异常
at com.imooc.test.TryDemoFive.test3(TryDemoFive.java:29)
at com.imooc.test.TryDemoFive.main(TryDemoFive.java:7)

2.打印出异常链的全部信息
https://docs.oracle.com/javase/8/docs/api/
方案一:
Throwable(String message, Throwable cause)
方案2:
initCause(Throwable cause)

package com.imooc.test;

public class TryDemoFive {

    public static void main(String[] args) {
        try {
            test3();
        } catch (Exception e) {
            
            e.printStackTrace();
        }

    }
    public static void test1() throws Exception {
        throw new Exception("test1异常");
    }
    
    public static void test2() throws Exception {
        try {
            test1();
        } catch (Exception e) {
            throw new Exception("test2异常",e);//方案1:将上面捕获的异常对象传入
        }
    }
    public static void test3() throws Exception {
        try {
            test2();
        } catch (Exception e) {
            //throw new Exception("test3异常",e);
            Exception e1 = new Exception("test3异常");//方案2:initCause方法
            e1.initCause(e);
            throw e1;
            
        }
    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 八、深入理解java异常处理机制 引子try…catch…finally恐怕是大家再熟悉不过的语句了, 你的答案是...
    壹点零阅读 1,720评论 0 0
  • 什么是异常? 异常本质上是程序上的错误,错误在我们编写程序的过程中会经常发生,包括编译期间和运行期间的错误。 编译...
    若兮缘阅读 3,663评论 0 11
  • 目录介绍 10.0.0.1 见过哪些运行时异常?异常处理机制知道哪些?从异常是否必须需要被处理的角度来看怎么分类?...
    杨充211阅读 559评论 0 1
  • Java异常简介 Java异常是Java提供的一种识别及响应错误的一致性机制。Java异常机制可以使程序中异常处理...
    JourWon阅读 1,333评论 0 5
  • Java异常 异常指不期而至的各种状况,如:文件找不到、网络连接失败、非法参数等。异常是一个事件,它发生在程序运行...
    java部落阅读 3,488评论 1 13

友情链接更多精彩内容