try catch 中的finally什么时候运行

try catch 中的finally什么时候运行

在Java、C#等编程语言中,try-catch-finally语句块用于处理异常。finally块的执行时机通常是在try块中的代码执行完毕之后,无论try块中的代码是否引发了异常。

具体执行顺序如下:

1、try块中的代码首先被执行。

2、如果try块中的代码没有引发异常,那么catch块将被跳过,然后执行finally块。

3、如果try块中的代码引发了异常,那么相应的catch块将被执行。无论是否有匹配的catch块,finally块都将被执行。

4、如果在try或catch块中有return语句,finally块仍然会在方法返回之前被执行。

5、如果在finally块中也出现了异常,那么这个异常将覆盖try或catch块中的异常。

下面是一个简单的Java示例:

复制代码
public class TryCatchFinallyExample {  
    public static void main(String[] args) {  
        try {  
            System.out.println("Inside try block");  
            int result = 10 / 0; // 这将引发ArithmeticException异常  
        } catch (ArithmeticException e) {  
            System.out.println("Inside catch block");  
        } finally {  
            System.out.println("Inside finally block");  
        }  
    }  
}

在这个示例中,try块中的代码引发了算术异常,因此将执行相应的catch块。然后,无论是否发生异常,都将执行finally块。

相关推荐
可可嘻嘻大老虎4 分钟前
SpringBoot拦截器防重复提交实战
java·spring boot·后端
cheems95279 分钟前
[开发日记]Spring Boot + MyBatis-Plus 抽奖系统排障实录:从 JWT 被拦截到雪花 ID 失控,我是怎样一步步修通登录与人员列表的
spring boot·后端·mybatis
我登哥MVP13 分钟前
Spring Boot 从“会用”到“精通”:Rest风格原理
java·spring boot·后端·spring·maven·intellij-idea·mybatis
我登哥MVP16 分钟前
Spring Boot 从“会用”到“精通”:静态资源原理
java·spring boot·后端·spring·tomcat·maven·intellij-idea
奋斗的袍子00717 分钟前
springboot集成国密算法SM2
java·spring boot·算法
caibixyy17 分钟前
Springboot + flowable6.8.0
spring boot·flowable6.8.0
JAVA面经实录91717 分钟前
SpringBoot 全套完整版学习文档(零基础+实战+面试+源码)
java·spring boot·spring·架构
小马爱打代码22 分钟前
SpringBoot + SpringCloud Gateway + Sentinel + Redis:API 网关层的接口限流、黑名单拦截与用户认证
spring boot·spring cloud·gateway
爱吃羊的老虎13 小时前
【JAVA】python转java:Spring Boot 入门
java·spring boot·python
_qingche14 小时前
H2 数据库到 MySQL 数据迁移
java·数据库·spring boot·mysql·spring·重构·kotlin