Java之异常

Java之异常

概述

异常是什么?

异常是代码在编译或者执行的过程中可能出现的错误

异常分为几类?

  1. 编译时异常、运行时异常。
  2. 编译时异常:没有继承RuntimeExcpetion的异常,编译阶段就会出错。
  3. 运行时异常:继承自RuntimeException的异常或其子类,编译阶段不报错,运行可能报错。

学习异常的目的?

避免异常的出现,同时处理可能出现的异常,让代码更稳健。

运行时异常

直接继承自RuntimeException或者其子类,编译阶段不会报错,运行时可能出现的错误。

一般是指程序员业务没有考虑好或者是编程逻辑不严谨引起的错误。

事例

  1. 数组索引越界异常:ArraylndexOutofBoundsException
  2. 空指针异常:NullPointerException,直接输出没有问题,但是调用空指针的变量的功能就会报错
  3. 数学操作异常: ArithmeticException
  4. 类型转换异常: ClassCastException
  5. 数字转换异常: NumberFormatException

编译时异常

不是RuntimeException或者其子类的异常,编译阶就报错,必须处理,否则代码不通过

示例

String date = "2015-01-12 14:27:56";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = sdf.parse(date); //日期解析异常
System.out.println(d);

作用

  1. 是担心程序员的技术不行,在编译阶段就爆出一个错误,目的在于提醒不要出错!
  2. 编译时异常是可遇不可求。遇到了就遇到了呗。

异常处理机制

默认异常处理机制

  1. 默认会在出现异常的代码那里自动的创建一个异常对象:ArithmeticException。
  2. 异常会从方法中出现的点这里抛出给调用者,调用者最终抛出给JVM虚拟机
  3. 虚拟机接收到异常对象后,先在控制台直接输出异常栈信息数据
  4. 直接从当前执行的异常点干掉当前程序
  5. 后续代码没有机会执行了,因为程序已经死亡。
public static void main(String[] args) {
        System.out.println("程序开始===========");
        divide(10,0);
        System.out.println("程序结束===========");
    }
    public static void divide(int a , int b){
        System.out.println(a);
        System.out.println(b);
        int c = a / b;
        System.out.println(c);
    }

默认的异常处理机制并不好,一旦真的出现异常,程序立即死亡!

编译时异常处理机制

  1. 出现异常直接抛出去给调用者,调用者也继续抛出去 (throws)
  2. 出现异常自己捕获处理,不麻烦别人 (try-catch)
  3. 前两者结合,出现异常直接抛出去给调用者,调用者捕获处理 (两者结合)
throws

用在方法上,可以将方法内部出现的异常抛出去给本方法的调用者处理.

这种方式并不好,发生异常的方法自己不处理异常,如果异常最终抛出去给虚拟机将引起程席死亡

格式:
方法 throws 异常1,异常2,异常3...{
}
规范做法:
方法 throws Exception{
}
public static void main(String[] args) throws Exception {
    System.out.println("程序开始========");
    parseTime("2023-07-30 14:42:15");
    System.out.println("程序结束========");
}

    private static void parseTime(String date) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = sdf.parse(date);
        System.out.println(d);

        InputStream i = new FileInputStream("C:/auif.jdg");
    }
try-catch
  1. 监视捕获异常,用在方法内部,可以将方法内部出现的异常直接捕获处理
  2. 这种方式还可以,发生异常的方法自己独立完成异常的处理,程序可以继续往下执行。
格式:
try{
	// 监视可能出现异常的代码!
}catch(异常类型1 变量){
	//处理异常
}catch(异常类型2 变量){
	//处理异常
}...
建议格式:
try{
	//可能出现异常的代码!
}catch(Exception e){
	e.printStackTrace(); //直接打印异常栈信息
}...
Exception 可以捕获处理一切异常类型!

代码:

try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date d = sdf.parse(date);
            System.out.println(d);

            InputStream i = new FileInputStream("C:/auif.jdg");
        }
        catch (Exception e) {
            e.printStackTrace();//打印异常栈信息
throws 和try-catch结合
public static void main(String[] args) {
        System.out.println("程序开始========");
        try {
            parseTime("2023-07-30 14:42:15");
            System.out.println("功能操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("功能操作失败");
        }
        System.out.println("程序结束========");
    }
    private static void parseTime(String date) throws Exception {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date d = sdf.parse(date);
            System.out.println(d);

            InputStream i = new FileInputStream("C:/auif.jdg");
    }

自定义异常

1、自定义编译时异常

  1. 定义一个异常类继承Exception.
  2. 重写构造器。
  3. 在出现异常的地方用throw new 自定义对象抛出
  4. 作用:编译时异常是编译阶段就报错,醒更加强烈,一定需要处理!!

代码实现

  1. 自定义的异常类
public class IthengAgeIlleagalException extends Exception{

    public IthengAgeIlleagalException() {
    }

    public IthengAgeIlleagalException(String message) {
        super(message);
    }
}
  1. Test类
public class ExceptionDemo {
    public static void main(String[] args) {
        try {
            checkAge(-34);
        } catch (IthengAgeIlleagalException e) {
            e.printStackTrace();
        }
    }
    public static void checkAge(int age) throws IthengAgeIlleagalException {
        if (age < 0 || age >200){
            //抛出去一个异常
            //throw:  在方法内部直接创建一个异常对象,并从此点抛出
            //throws: 用在方法申明上的,抛出方法内部的异常
            throw new IthengAgeIlleagalException(age + " is illegal");
        }else{
            System.out.println("年龄合法,给其推荐商品");
        }
    }
}

2、自定义运行时异常

  1. 定义一个异常类继承RuntimeException
  2. 重写构造器
  3. 在出现异常的地方用throw new 自定义对象抛出!
  4. 作用:提醒不强烈,编译阶段不报错!!运行时才可能出现!!

代码实现

  1. 自定义的运行时异常类
public class IthengAgeRuntimeException extends Exception{

    public IthengAgeRuntimeException() {
    }

    public IthengAgeRuntimeException(String message) {
        super(message);
    }
}
  1. Test类
public static void main(String[] args) {
		try {
            checkAge(-34);
        } catch (IthengAgeRuntimeException e) {
            e.printStackTrace();
            System.out.println("出错了");
        }
    }
    
        public static void checkAge(int age) throws IthengAgeRuntimeException{
            if (age < 0 || age > 200) {
                throw new IthengAgeRuntimeException(age + " is illegal");
            } else {
                System.out.println("年龄合法,给其推荐商品");
            }
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值