JAVA基础学习(七)------异常机制

什么是异常

  • 实际工作中,遇到的情况不可能是非常完美的,软件运行过程中,非常可能遇到问题,我们叫异常,英文是:Exception

  • 异常指程序运行中出现的不期而至的各种状况,如:文件找不到、网络连接失败、非法参数等

  • 异常生在程序运行期间,他影响了正常的程序执行流程

    public class Demo01 {
        public static void main(String[] args) {
            new Demo01().a();
        }
        public void a(){
            b();
        }
        public void b(){
            a();
        }
    }
    //Exception in thread "main" java.lang.StackOverflowError
    
    public class Demo01 {
        public static void main(String[] args) {
            System.out.println(11/0);
        }
    }
    //Exception in thread "main" java.lang.ArithmeticException: / by zero
    

异常简单分类:

检查性异常:

最具代表的检查性异常是用户错误或用户问题引起的异常,这是程序员无法预见的。

例:要打开一个不存在的文件时,一个异常就发生了,这些异常在编译时不能被简单的忽略

运行时异常:

也是最可能被程序员避免的异常,与检查性异常相反,运行时异常可以在编译时被忽略

错误ERROR:

错误不是异常,而是脱离程序员控制的问题,错误在代码中通常被忽略

例:当栈溢出时,一个错误就发生了,它们在编译也检查不到的

异常体系结构

  • Java把异常当作对象来处理,并定义了一个基类java.lang.Throwable作为所有异常的超类

  • 在Java API中已经定义了许多异常类,这些异常分为两大类,错误Error和异常Exception

  • 一般来说Exception可以预见,Error不可预见

在这里插入图片描述

Error

  • Error类对象由Java虚拟机生成并抛出,大多数错误与代码编写者所执行的操作无关
  • Java虚拟机运行错误(Virtual MachineError),当JVM不再有继续执行操作所需的内存资源时,将出现OutOfMemoryError,这些异常发生时,Java虚拟机(JVM)一般会选择线程终止
  • 还有发生在虚拟机试图运行应用时,如类定义错误(NoClassDefFoundError),链接错误(LinkageError),这些错误是不可查的,因为他们在应用程序的控制和处理能力之外,而且大多数是程序运行时不允许出现的状况

Exception

  • 可大体分为运行时异常和非运行时异常

  • 在 Exception分支中有一个重要的子类 RuntimeException(运行时异常)

    包括:

    1、ArraylndexOutofBounds Exception(数组下标越界)

    2、NullPointerException(空指针异常)

    3、ArithmeticException(算术异常)

    4、Missing Exception(丢失资源)

    5、ClassNotFoundException(找不到类)等异常,这些异常是不检查异常,程序中可以选择捕获处理,也可以不处理

  • 这些异常一般是由程序逻辑错误引起的,程序应该从逻辑角度尽可能避免这类异常的发生

Error和 Exception的区别:

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

异常处理机制

  • 抛出异常

  • 捕获异常

  • 异常处理五个关键字:trycatchfinallythrowthrows

  • 格式:

    try {//try监控区域
                
            }catch (//想要捕获的异常类型
    					){
        //捕获异常
            }finally {
                //无论有没有异常finally里的话都执行
                //finally 可以不要 ,作用:假设IO,资源需要关闭,一般用finally
            }
    
    public class Test {
        public static void main(String[] args) {
            //Exception in thread "main" java.lang.ArithmeticException: / by zero
            int a = 1;
            int b = 0;
            try {//try监控区域
                System.out.println(a/b);
            }catch (ArithmeticException e){
                System.out.println("程序出现异常,变量B不能为0");
            }finally {
                //无论有没有异常finally里的话都执行
                //finally 可以不要 ,作用:假设IO,资源需要关闭,一般用finally
                System.out.println("finally");
            }
        }
    }
    //程序出现异常,变量B不能为0
    //finally
    
  • 假设要捕获多个异常,需要从小到大来捕获

    public class Test {
        public static void main(String[] args) {
            try {//try监控区域
                new Test().a();
            }catch (Error e){
                System.out.println("Error");
            }catch (Exception e){
                System.out.println("Exception");
            }catch (Throwable t){
                System.out.println("Throwable");
            }
            finally {
                //无论有没有异常finally里的话都执行
                System.out.println("finally");
            }
        }
        public void a(){
            b();
        }
        public void b(){
            a();
        }
    }
    
  • 自动生成trycatch快捷键:ctrl+Alt+T

    public class Test2 {
        public static void main(String[] args) {
            int a = 1;
            int b = 0;
            try {
                System.out.println(a/b);
            } catch (Exception e) {
                System.exit(0);//主动结束程序(括号内的数字随便填)
                e.printStackTrace();//打印错误的栈信息
            } finally {
                
            }
        }
    }
    
  • 主动抛出异常(一般在方法中使用)

    public class Test {
        public static void main(String[] args) {
            //Exception in thread "main" java.lang.ArithmeticException: / by zero
            int a = 1;
            int b = 1;
            try {//try监控区域
                if(b==0){//主动抛出异常 throw  throws完全不一样
                    throw new ArithmeticException();
                }
                System.out.println(a/b);
            }catch (Exception e){
                System.out.println("Exception");
            }finally {
                //无论有没有异常finally里的话都执行
                System.out.println("finally");
            }
        }
    }
    
  • 在方法中抛出异常(用throw

    public class Test {
        public static void main(String[] args) {
            //Exception in thread "main" java.lang.ArithmeticException: / by zero
            int a = 1;
            int b = 0;
            new Test().test(1,0);
        }
        public void test(int a,int b){
            if(b==0){//主动抛出异常 throw  throws完全不一样
                throw new ArithmeticException();
            }
        }
    }
    //Exception in thread "main" java.lang.ArithmeticException
    
  • 假设方法中无法处理这个异常,在方法上抛出异常(用throws

    public class Test {
        public static void main(String[] args) {
            //Exception in thread "main" java.lang.ArithmeticException: / by zero
            try {
                new Test().test(1,0);
            } catch (ArithmeticException e) {
                e.printStackTrace();
            } finally {
    
            }
        }
        public void test(int a,int b)throws ArithmeticException{
            System.out.println(a/b);
        }
    }
    

自定义异常

  • 使用Java内置的异常类可以描述在编程时岀现的大部分异常情况,除此之外,用户还可以自定义异常,用户自定义异常类,只需继承 Exception类即可

  • 在程序中使用自定义异常类,大体可分为以下几个步骤

    1、创建自定义异常类

    2、在方法中通过throw关键字抛出异常对象

    3、如果在当前抛出异常的方法中处理异常,可以使用try- catch语句捕获并处理,否则在方法的声明处通过throws关键字指明要抛岀给方法调用者的异常,继续进行下一步操作

    4、在岀现异常方法的调用者中捕获并处理异常

//自定义的异常类
public class MyException extends Exception{
    //传递数字>10
    private int detail;

    public MyException(int detail) {
        this.detail = detail;
    }
    //toString:异常的打印信息
    @Override
    public String toString() {
        return "MyException{" + detail + '}';
    }
}

public class Test {
    //可能会存在异常的方法
    static void test(int a) throws MyException {
        System.out.println("传递的参数为:"+a);
        if(a>10){
            //可以抛出或在方法中捕获
            throw new MyException(a);
        }
        System.out.println("ok");
    }

    public static void main(String[] args) {
        try {
            test(11);
        } catch (MyException e) {
            //可以增加一些处理异常的代码
            System.out.println("MyException:"+e);
        }
    }
}

实际应用中的经验总结

  • 处理运行时异常时,采用逻辑去合理规避同时辅助try- catch处理
  • 在多重 catch块后面,可以加一个 catch( Exception)来处理可能会被遗漏的异常
  • 对于不确定的代码,也可以加上try- catch,处理澘在的异常
  • 尽量去处理异常,切忌只是简单地调用 printStackTrac()去打印输出
  • 具体如何处理异常,要根据不同的业务需求和异常类型去决定
    异常的代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值