java中的try-catch-finally的处理流程介绍

本文详细介绍了异常处理的基本概念和流程,包括try、catch和finally块的作用及使用方式。通过两个具体的代码示例,展示了如何正确地捕获和处理异常,确保程序的稳定运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

异常处理是为了保证程序出现了异常的时候,及时地去捕获到异常,并使程序继续处理的手段。

常用的写法是

try{

}catch(Exception e){

}finally{

}

try块是可能抛出异常的代码块,
catch块是处理try块中抛出的异常用的。可以有一个或者多个catch块。
finally块是最后的处理块。不管try是否抛出异常,也不管catch是否捕获到了抛出的异常,该段代码总会运行。
try块后面可以有catch或者finally块,或者catch和finally块都有。但是不能catch和finally块都没有。

程序流程
当try块的代码没有异常抛出的时候,try块执行完毕之后,程序会顺序执行finally块的代码。
当有异常抛出的时候,后续的一个或者多个catch的定义中,应该有一个最先匹配到的异常来处理捕获到的异常,然后程序在进入finally代码块。

如果程序没有定义catch块或者catch块代码不能捕获到程序的异常,如果有finally代码块,程序也是先执行finally代码块,然后再异常退出流程。如果finally代码块后面还有代码,则这些代码不会被执行。


代码举例A:

代码的目的:原本是想让代码执行两遍,实际上,因为有异常抛出,所以程序不能执行两遍。

public class TryTestA {
	public static void main(String[] args){
		System.out.println("===TryTestA===");
		for(int x = 0; x < 2; x++){
			try{
				System.out.println("this is try block before exception");
				System.out.println(10/0);
				System.out.println("this is try block after exception");
			}finally{
				System.out.println("this is finally block");
			}
			
			System.out.println("this is other block afer finally block. x is "+x);
		}
	}

}
代码的结果为:

===TryTestA===
this is try block before exception
this is finally block
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at com.baby.TryTestA.main(TryTestA.java:9)

结果说明:

程序的目的是将try块执行两遍,但是因为抛出了异常,程序并没有捕获到异常,所以,执行了一遍就退出了。在退出之前,程序执行了finally里面的代码。

代码举例B:

代码的目的:让代码执行两遍来测试程序的流程

public class TryTestB {
	public static void main(String[] args) throws ArithmeticException {
		System.out.println("===TryTestB===");
		for (int x = 0; x < 2; x++) {
			try {
				System.out.println("this is try block before exception");
				System.out.println(10 / 0);
				System.out.println("this is try block after exception");
			} catch (ArithmeticException e) {
				System.out.println("this is catch(ArithmeticException e) block");
			} catch (Exception e) {
				System.out.println("this is catch(Exception e) block");
			} finally {
				System.out.println("this is finally block");
			}

			System.out.println("this is other block afer finally block. x is " + x);
		}
	}

}
代码的结果为:

===TryTestB===
this is try block before exception
this is catch(ArithmeticException e) block
this is finally block
this is other block afer finally block. x is 0
this is try block before exception
this is catch(ArithmeticException e) block
this is finally block
this is other block afer finally block. x is 1

结果说明:

在try块抛出的异常,被catch捕获到,然后程序继续向下处理。整个流程一共处理了两遍。符合预期。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值