java异常处理

一、Exception类的使用

异常的作用:增强程序的健壮性
所有的异常类是从 java.lang.Exception 类继承的子类。
Exception 类是 Throwable 类的子类。除了Exception类外,Throwable还有一个子类Error 。
Java 程序通常不捕获错误。错误一般发生在严重故障时,它们在Java程序处理的范畴之外。
Error 用来指示运行时环境发生的错误。
例如,JVM 内存溢出。一般地,程序不会从错误中恢复。
异常类有两个主要的子类:IOException 类和 RuntimeException 类。
在这里插入图片描述

二、代码示例

1.简单示例

  • try用来检测异常
  • catch用来捕获异常
  • finally用来释放资源
public class Demo1_exception {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5};
        try {
            System.out.println(arr[10]);
        }/*catch (ArrayIndexOutOfBoundsException index){
            System.out.println("索引越界");
        }*/catch (Exception e){
            System.out.println("老大");
        }
    }
}

输出:
在这里插入图片描述


2.抛异常

  • 运行时异常的抛出可以处理也可以不处理
  • 编译时必须处理

下面定义一个person类,规定年龄在18-50之间,超出的话就向上抛异常

代码:

public class Demo3_thorw {
    public static void main(String[] args) throws Exception {
        Person p1 = new Person();
        p1.setName("张阿三");
        p1.setAge(90);
        System.out.println(p1.getAge());
    }
}
class Person{
    private String name;
    private int age;
    public Person(){}
    public Person(String name,int age){
        this.name = name;
        this.age = age;
    }

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

    public void setAge(int age) throws AgeOutOfBoundsException{
        if (age>=18 && age<=50) {
            this.age = age;
        }else{
            throw new AgeOutOfBoundsException("年龄非法");
        }
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

自定义异常:

class AgeOutOfBoundsException extends Exception{
    public AgeOutOfBoundsException(String message) {
        super(message);
    }
}

3.finally详解

finally控制的语句一定会执行,前面遇到return也不会结束,除非退出虚拟机,system.exit(0)
用于释放资源,在io流和数据库中出现
final:修饰类不能被继承,修饰方法不能被重写,修饰变量只能被赋值一次
finalize:垃圾回收器
千万不要在fianlly里面写返回语句

代码:


public class Demo4_finally {
    /*
    * finally控制的语句一定会执行,前面遇到return也不会结束,除非退出虚拟机,system.exit(0)
    * 用于释放资源,在io流和数据库中出现
    * final:修饰类不能被继承,修饰方法不能被重写,修饰变量只能被赋值一次
    * finalize:垃圾回收器
    * 千万不要在fianlly里面写返回语句
    * */
    public static void main(String[] args) {
        try {
            System.out.println(10/0);
        }catch (Exception e){
            System.out.println("error");
            return;
        }finally {
            System.out.println("finally");
        }
    }
}

输出:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝朽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值