(十六)异常总结

异常


概念

异常(Exception)是指程序在运行过程中所发生的不正常事件,它会中断正在运行的程序

异常不是错误,更不是程序的逻辑错误


异常处理机制

异常会导致程序中断运行

在这里插入图片描述

异常处理可以保证程序出现异常后,往正确方向运行

在这里插入图片描述


异常处理


异常对象

异常对象时出现异常时的那条语句产生的(jvm自动创建)

Exception是所有异常类的子类

方法

toString返回异常类型和异常信息
getMessage返回异常信息
printStackTrace打印堆栈信息,位置不固定

try...catchtry...catch...finally

try{
    //可能产生异常的代码块
}catch(异常类型 ex){
    //异常处理
}


try…catch

三种处理情况

  1. 没有发生异常,程序正常执行
  2. 出现异常,catch捕获异常并进行处理,处理完毕,程序继续执行
  3. 异常不匹配,程序中断

例子

import java.util.Scanner;

public class Test01 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输出第一个数");

        int r =0;
        try{
           int num1 =sc.nextInt();
           //输入a 产生异常对象异常 InputMismatchException ex =new InputMismatchException()
           //程序不能继续执行,转入异常处理
            System.out.println("请输入第二个数");
            int num2 = sc.nextInt();
            r =num1 /num2;

            //异常捕获(异常处理) Exception e =ex(多态) ,jvm问ex你是不是Exception对象 (ex instanceOf Exception)
        }catch(Exception e){
            System.out.println("出现问题");
        }

        System.out.println(r);
    }
}

try…catch…finally

finally代码块用于处理异常后的收尾工作,不管是否发生异常,finally总执行

finally 唯一不执行的情况:jvm 正常退出(System.exit(0))

finally 的收尾工作包含释放内存、关闭文件、关闭网络连接、关闭数据库等

例子:

public class Test03 {
    public static void main(String[] args) {
        int r = test();
        System.out.println(r);
    }

    public static int test(){
        int m =10;
        int r =0;
        try {
            r = m/r;
            return r;
            } catch (Exception e) {
            System.out.println("出问题了");
            return r;
        }finally {
           
            m++;
            r=-1;      
        }
    }
}
返回结果是: 出问题了
           r=0;
分析:为什么r等于0 ,finally 是优先于return,但是finally只用于收尾工作,
    所以需要注意,finally 块中不要再添加业务需求.
  • 存在 return 的 try…catch…finally 块,finally 先执行,然后执行 return
  • return 总是最后执行的


异常分类

在 Java 中,Throwable 类是 Java 语言中所有错误(Error)或异常的父类。


Error

Error表示代码运行时JVM出现的问题.一般来说是程序员处理不了的,只能避免


Exception

Exception表示程序在运行时出现的一些不正常情况,程序员可以去处理的

异常分为运行时异常检查时异常


运行时异常RuntimeException

在程序运行过程中,可处理,也可以不处理,其父类是RuntimeException

常见的运行时异常

1.InputMismatchException:输入不匹配异常
2.ArithmeticException:数学计算异常 //除数不能为0 
    
3.IndexOutOfBoundsException:下标/索引越界异常
   /* ArrayList<String> list =new ArrayList<>();
    String item = list.get(150);
    System.out.println(item);*/

4.ArrayIndexOutOfBoundsException : 数组下标越界异常
5.StringIndexOutOfBoundsException : 字符串下标越界 

6.NullPointerException : 空指针异常
   /*String str =null;
   char c =str.charAt(0);
   System.out.println(c);*/

7.ClassCastException : 强制类型转换异常
    
8.NumberFormatException : 数字格式转换异常,如把"abc"转换成数字
    Integer i = Integer.valueOf("abc");

9.IllegalArgumentException : 方法接收到非法参数    

检查时异常Checked Exception

也称为编译时异常,在编译期间程序出现不正常的情况,程序必须做出处理,否则编译不通过

常见的检查时异常

1.ClassNotFoundException : class 没找到异常
2.FileNotFoundException : 未见未找到异常
3.IOException:IO 异常
4.SQLException : 数据库相关异常
5.UnsupportedEncodingException : 不支持的字符串编码异常


声明异常

在 Java 语言中通过 throws 声明某个方法可能抛出的各种异常。


throws

方法定义者在定义方法时,认为可能会出现异常,但是却不知道怎么处理时,

方法定义者可以选择声明异常(异常上抛),使用throws关键字

[修饰符] 返回值类型 方法名(形参列表) throws 异常 1,异常 2,、、、{
}

声明异常根据异常分类来决定调用者是否必须处理该方法产生的异常,如果要求外界必须处理,则声明检查时异常,否则声明运行时异常

声明异常与重载的关系
  • 当父类声明运行时异常时,子类可以声明运行时异常或者不声明
  • 父类声明检查时异常时,子类可以声明检查时异常或者不声明或者运行时异常


throw

在实际开发过程中,开发者也可以根据程序的需要,手动抛出异常,通过 throw 关键字。

public void setGender(String gender) throws Exception {
    if (gender.equals("男") ||gender.equals("女")){
        this.gender = gender;

    }else{
        //1.
        Exception ex = new Exception("性别不合法");
        throw ex;
        //2.
        //throw new Exception("性别不合法");
        
    }
}


自定义异常

当 JDK 中的异常类型不能满足程序的需要时(也即需要定义具体的业务异常时),可以自定义 异常。

例子:

声明一个性别异常

ublic class GenderException extends Exception{
    public GenderException() {
        super();
    }

    public GenderException(String message) {
        super(message);
    }

    public void log(){
        System.out.println("I am a 日志");
    }
}

定义学生类

package com.k.day17;

public class Student {
    private  String name;
    private String gender;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }
     //抛出性别异常
    public void setGender(String gender) throws GenderException {
        if (gender.equals("男") ||gender.equals("女")){
            this.gender = gender;

        }else{
            
            //3.自定义异常
            throw  new GenderException("性别不对");
        }
    }

    public Student() {
    }

    public Student(String name, String gender) {
        this.name = name;
        this.gender = gender;
    }


}

测试类

   public static void main(String[] args) {
        Student student = new Student();
       //处理异常
        try {
            student.setGender("小姐姐");
        } catch (GenderException e) {
            e.printStackTrace();
        }


    }
}
        this.gender = gender;
    }


}

测试类

   public static void main(String[] args) {
        Student student = new Student();
       //处理异常
        try {
            student.setGender("小姐姐");
        } catch (GenderException e) {
            e.printStackTrace();
        }


    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值