Java入门Day7:异常,Javase结束

1. 什么是异常?

在程序运行的过程中,出现了意料之外的情况,就是异常。比如:输入的格式不规范,查找的地址不存在,内存溢出等等。
我们通过Exception 抛出异常,使我们程序的运行不至于崩溃。

  • 检查性异常:用户错误或问题引起的异常,比如输入不规范。
  • 运行时异常:是可以避免和修正的,可以在编译时被忽略。
  • 错误:错误不是异常,是脱离控制的,比如内存溢出。ERROR
    Java把异常当做对象来处理,并提供了java.lang.Throwable作为所有异常的超类。

2. Error错误

  • Error是错误,是由JVM生成并抛出的,大多数时候与代码无关。
  • 发生Error时,一般程序会直接崩溃。

3.Exception异常

3.1 RuntimeException运行时异常

  • ArrayIndexOutOfBoundsException 数组下标越界异常
  • NullPointerException 空指针异常
  • ArithmeticException 算术异常
  • MissResourceException 资源丢失异常
  • ClassNotFoundException 类丢失异常
    包括但不限于这些异常都是不检查异常,程序中可以选择捕获处理,也可以选择忽略。
    这些异常都是由程序逻辑错误引起的,应该尽量避免。

3.2 抛出异常

  • throw 一般在方法中使用
public class Demo01 {
    public static void main(String[] args) {
        new Demo01().test(1, 0);
    }
    public void test(int a, int b){
        if (b==0){
            throw  new ArithmeticException();
        }
        System.out.println(a/b);
    }
}
  • throws在方法声明中使用
public class Demo01 {
    public static void main(String[] args) throws ArithmeticException{
        new Demo01().test(1, 0);
    }
    public void test(int a, int b){
        System.out.println(a/b);
    }
}

3.3 捕获异常

public class Demo01 {
    public static void main(String[] args) {
        int a = 0 ;
        int b = 1 ;

        try { //监控区域
            System.out.println(b/a);
        }catch (ArithmeticException e){//捕获异常
            System.out.println("异常");
        }finally {//忽略异常
            System.out.println("F");
        }
    }
}
  • try 监控区域是否有异常。
  • catch() 捕获异常,可以有多个catch() 捕获不同的异常,但从上往下的异常级别应该是从小到大的。
  • finally 忽略异常。
  • trycatch() 必须一起出现
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值