Java中异常的学习

Java中异常的学习


一、基础用法

主要涉及到这几个关键词
1.try:try 语句块中放置可能会抛出异常的代码。
2.catch:catch 语句块中放置用来处理异常的代码,try 和 catch 往往要搭配使用。当 try 中出现异常的时候,就会进入 catch 中执行。
3.throw:主动抛出一个异常对象。
4.throws:某个方法可能会抛出某些异常。
5.finally:一般用于异常处理完的收尾工作。

二、认识异常

1.除以0

System.out.println(10 / 0);

// 执行结果
Exception in thread "main" java.lang.ArithmeticException: / by zero

2.数组下标越界

int[] arr = {1, 2, 3}; System.out.println(arr[100]);

// 执行结果
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100

3.访问 null 对象

public class Test { public int num = 10;
public static void main(String[] args) { Test t = null; System.out.println(t.num);
}
}

// 执行结果
Exception in thread "main" java.lang.NullPointerException

三、异常的基本用法

1.捕获异常

基本语法

try{
有可能出现异常的语句 ;
}[catch (异常类型 异常对象) {
} ... ]
[finally {
异常的出口
}]

代码示例1 不处理异常

int[] arr = {1, 2, 3}; System.out.println("before"); System.out.println(arr[100]); System.out.println("after");

// 执行结果
before
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100

我们发现一旦出现异常, 程序就终止了. after 没有正确输出.

代码示例2 使用 try catch 后的程序执行过程

int[] arr = {1, 2, 3};


try {
System.out.println("before"); System.out.println(arr[100]); System.out.println("after");
} catch (ArrayIndexOutOfBoundsException e) {
// 打印出现异常的调用栈
e.printStackTrace();
}
System.out.println("after try catch");

// 执行结果
before java.lang.ArrayIndexOutOfBoundsException: 100
at demo02.Test.main(Test.java:10) after try catch

2.异常处理流程

1.程序先执行 try 中的代码
2.如果 try 中的代码出现异常, 就会结束 try 中的代码, 看和 catch 中的异常类型是否匹配.
3.如果找到匹配的异常类型, 就会执行 catch 中的代码
4.如果没有找到匹配的异常类型, 就会将异常向上传递到上层调用者.
5.无论是否找到匹配的异常类型, finally 中的代码都会被执行到(在该方法结束之前执行).
6.如果上层调用者也没有处理的了异常, 就继续向上传递.
7.一直到 main 方法也没有合适的代码处理异常, 就会交给 JVM 来进行处理, 此时程序就会异常终止.

3.Java 异常体系

Java 内置了丰富的异常体系, 用来表示不同情况下的异常. 下图表示 Java 内置的异常类之间的继承关系:
在这里插入图片描述
在这里插入图片描述

四、注意事项

1.自定义异常通常会继承自 Exception 或者 RuntimeException
2.继承自 Exception 的异常默认是受查异常
3.继承自 RuntimeException 的异常默认是非受查异常.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Wmx-98

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

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

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

打赏作者

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

抵扣说明:

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

余额充值