Java 程序使用 finally 块捕获异常

2024 年 9 月 10 日 | 阅读 3 分钟

块是 IT 领域中最有用的行业实践之一。在 IT 项目的开发周期中,需要创建和维护一些必要代码。这些必要的代码行必须放在 try 块中,以标记它们为干净代码,例如,在开发的项目中关闭文件或关闭建立的连接。

Finally 块在三种情况下广泛使用,下面将通过 Java 编程语言的相关代码进行讨论。

情况 1:当没有发生异常时

Java 代码

输出

java -cp / tmp /pk kY 1yo G xa  JTP
hey! Coder, we are inside the try block now
42
Hey, code,r finally: i executed consistently has taken place!

情况 2:当异常发生并由 Catch 块处理时

Java 代码

输出

java -cp  /tmp /pk kY 1y oG X a JTP
hey! Coder, we are inside the try block now
hey, coder, the catch: exception has been handled.
Hey coder, finally: i executed consistently has taken place!

情况 3:当异常发生但未由 Catch 块处理时

Java 代码

输出

java -cp  /tm p/pkkY 1yo GXa JTP
hey! Coder, we are inside the try block nowhere coder, finally: i executed always has taken place!
Exception in thread "main" java. Lang.ArithmeticException: / by zero at JTP.main(JTP.java:17)