296/297finally代码块和异常注意事项_多异常的捕获处理
finally代码块
fina!y:有一些特定的代码无论异常是否发生,都需要执行。
另外,因为异常会引发程序跳转,导致有些语句执行不到。而fnay就是解决这个问题的,在inal代码块中存放的代码都是一定会被执行的。
什么时候的代码必须最终执行?
当我们在tr语句块中打开了一些物理资源磁盘文件/网络连接/数据库连接等我们都得在使用完之后最终关闭打开的资源。
fina的语法
try....atch… finally:自身需要处理异常,最终还得关闭资源。
注意 c finally不能单独使用。
比如在我们之后学习的0流中,当打开了一个关联文件的资源,最后程序不管结果如何,都需要把这个资源关闭掉
必须执行的代码块,不管是否有异常产生,即使发生OutOfMemoryError也会执行,通常用于执行善后清理工作。如果finally代码块没有执行,那么有三种情况可能:
1、没有进入try代码块。
2、进入try代码块,但是代码运行中出现了死循环或死锁情况。
3、进入try代码块,但是执行了System.exit()操作。
案例1
public static void main(String[] args) {
try {
readFile("d:a.tx");
} catch (IOException e) {
e.printStackTrace();
}finally {
System.out.println("资源释放");
}
}
/*
如果传递的路径,不是.txt结尾
那么我们就抛出Io异常对象,告知方法的调用者,文件的后缀名不对
*/
public static void readFile(String fileName) throws IOException {
if(!fileName.equals(".txt")){
throw new IOException("文件的后缀名不对");
}
System.out.println("路径没有问题,读取文件");
}
案例2
class Demo
{
public int show(int index)throws ArrayIndexOutOfBoundsException
{
if(index<0)
throw new ArrayIndexOutOfBoundsException("越界啦!!");
int[] arr = new int[3];
return arr[index];
}
}
class ExceptionDemo5
{
public static void main(String[] args)
{
Demo d = new Demo();
try
{
int num = d.show(-1);
System.out.println("num="+num);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println(e.toString());
// return ;
// System.exit(0);//退出jvm。
}
finally//通常用于关闭(释放)资源。
{
System.out.println("finally");
}
System.out.println("over");
}
}
连接数据库
查询。Exception
关闭连接。
*/
/*
try catch finally 代码块组合特点:
1,
try catch finally
2,
try catch(多个)当没有必要资源需要释放时,可以不用定义finally。
3,
try finally 异常无法直接catch处理,但是资源需要关闭。
void show()throws Exception
{
try
{
//开启资源。
throw new Exception();
}
finally
{
//关闭资源。
/*
catch(Exception e)
{
}
*/
}
*/
finally:有一些特定的代码块无论异常是否发生,都需要运行。
格式:
try{
}
catch(异常变量){
}
catch(异常变量){
}
finally{
}
try {
readFile("D:\\\\a");
} catch(IOException e){
e.printStackTrace();
} finally {
System.out.println("资源释放");
}
System.out.println("后续代码");
异常注意事项_多异常的捕获处理
多个异常使用捕获又该如何处理呢?
1.多个异常分别处理。
2.多个异常一次捕获,多次处理。
3.多个异常一次捕获一次处理。
//1.多个异常分别处理。
try{
int[] arr = {1,2,3};
System.out.println(arr[3]);//ArrayIndexOutOfBoundsException: 3
}catch (ArrayIndexOutOfBoundsException e){
System.out.println(e);
}
try{
List<Integer> list = List.of(1,2,3);
System.out.println(list.get(3)); // IndexOutOfBoundsException: Index 3 out-of-bounds for length 3
}catch(ArrayIndexOutOfBoundsException e){
System.out.println(e);
}
//2.多个异常一次捕获,多次处理。如果catch中定义的异常变量存在字符类关系,
// 那么子类异常变量必须写在上面否则会报错。
try{
int[] arr = {1,2,3};
//System.out.println(arr[3]);//ArrayIndexOutOfBoundsException
List<Integer> list = List.of(1,2,3);
System.out.println(list.get(3)); // IndexOutOfBoundsException: Index 3 out-of-bounds for length 3
}catch(ArrayIndexOutOfBoundsException e){
System.out.println(e);
}catch (IndexOutOfBoundsException e){
System.out.println(e);
}
自定义异常
package com.company;
public class MyException extends Throwable {
public MyException(String ErrorMessagr) {
super(ErrorMessagr);
}
}
自定义异常
package com.company;
public class MyException extends Throwable {
public MyException(String ErrorMessagr) {
super(ErrorMessagr);
}
}
抛出异常
使用throws关键字抛出异常
通常用于声明方法时,用来指定方法可能抛出的异常
public class Shoot{
static void pop()throws NegativeArraySizeException{
int[]arr=new int[-3];
}
psvm{//简写
try{
pop();
}catch(NegativeArraySizeException e){
System.out.println("pop()方法抛出的异常");
}
}
}
适应throw关键字
通常用于方法体中
package com.company;
//异常捕获顺序实例
import java.lang.System;
import java.lang.ArithmeticException;
public class ExceptionOrder{
static int div(int x, int y) { //各种Exception都被捕获,函数无须声明异常
int r=0;
try{
//自己抛出异常对象
if(y==0) throw new ArithmeticException( );
r=x/y; }
catch(ArithmeticException ae) { System.out.print(ae.toString( )); throw ae; }
//处理完异常后可以继续抛出异常,交给上层调用者继续处理。注意即使这里抛出异常,同层的finally仍会执行
//catch子句里抛出异常,这个异常在div方法里没有处理,但是div可以不声明异常?为什么?因为ae是非必检
catch(Exception ae){//捕获各种Exception:若是第1个catch,则后续的catch子句无机会捕获
System.out.print(ae.toString( ));
}
finally{ r=-1; } //无论是否有异常,r=-1
return r;
}
public static void main(String[ ] args) {
try{ div(5, 0); } //调用div(5, 0)后,div函数的执行轨迹已用红色标出
catch(Throwable ae) { //任何异常都被捕获,包括Error类型异常
System.out.print(ae.toString( ));
//因此虽然div没有异常声明,在main里调用div也用了try/catch
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端