Flow control in try catch finally in Java

2025年5月8日 | 阅读6分钟

try-catch-finally 序列在引发异常时可能随时发生,所有这些都将在下一节中介绍,以及在提供的每种情况下控制流如何工作。在异常处理期间,我们将通过几个例子来演示 try、catch 和 finally 如何协同工作。以下是我们可以在其中确定它的两种情况。

1. try-catch 子句或 try-catch-finally 子句中的控制流

情况 1: try 块处理异常,而 catch 块处理它们。

情况 2: catch 块不处理 try 块中发生的异常。

情况 3: try 块不包含异常。

2. try-finally 子句中的控制流

情况 1: try 块中发生异常。

情况 2: try 块中未发生异常。

1. try-catch 子句或 try-catch-finally 子句中的控制流

try-catch 或 try-catch-finally 子句中,try 块首先运行。如果没有发生异常,控制将移至下一个语句,或者,如果存在,则移至 finally 块,并跳过 catch 块。如果发生异常,控制将移至适当的 catch 块。即使处理了异常或抛出了异常,finally 块(如果存在)总是在 try 或 catch 块之后运行,以确保清理任务已完成。

情况 1:try 块处理异常,而 catch 块处理它们

如果 try 块语句引发了异常,控制将移至适当的 catch 块,而 try 块的其余部分将不执行。一旦 catch 块被执行,控制将传递给 finally 块(如果存在),然后程序的其余部分将被运行。

i. try-catch 中的控制流

实施

输出

 
The Exception caught in the Catch block
Outside of the try-catch clause   

ii. try-catch-finally 子句中的控制流

实施

输出

 
The Exception caught in the Catch block
The finally block executed
Outside of the try-catch clause   

情况 2:catch 块不处理 try 块中发生的异常

在这种情况下,将使用默认的 方法 处理。如果存在 finally 块,则在执行完 finally 块后将使用默认的 方法 处理。

i. try-catch 中的控制流

实施

输出

 
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 8 out of bounds for length 8
at ControlTryCatchFinalExample3.main(ControlTryCatchFinalExample3.java:11)   

ii. try-catch-finally 子句中的控制流

实施

输出

 
The finally block executed
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 8 out of bounds for length 8 at ControlTryCatchFinalExample3.main(ControlTryCatchFinalExample3.java:11)   

情况 3:try 块不包含异常

Catch 块仅在响应异常时运行;因此,在这种情况下,它们永远不会运行。如果存在 finally 块,它将首先运行,然后程序的其余部分将执行。

i. try-catch 中的控制流

实施

输出

 
The catch block is getting executed...
Outside of the try-catch clause   

ii. try-catch-finally 子句中的控制流

实施

输出

 
The catch block is getting executed...
The finally block is usually executed
Outside of the try-catch clause   

2. try-finally 子句中的控制流

在这种情况下,无论 try 块中是否发生异常,finally 都将始终执行。但是,是否发生异常将决定控制流的执行方式。

在 try-finally 子句中,无论是否引发异常,try 块都会首先运行。如果没有发生异常,控制将通过 try 和 finally 块。由于没有 catch 块,在 try 块中发生的异常不会被直接处理;但是,在异常进一步传播之前,finally 块保证会运行。即使程序由于异常或 try 块中的 return 语句而突然终止,finally 块也始终执行,以确保完成关键的维护任务(如关闭资源)。

情况 1:try 块中发生异常

如果 try 块中发生异常,在 finally 块之后,默认的 异常处理 机制将接管控制流。

实施

输出

 
The finally block is usually executed
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 8 out of bounds for length 8
	at ControlTryCatchFinalExample7.main(ControlTryCatchFinalExample7.java:11)   

情况 2:try 块中未发生异常。

如果 try 块中没有异常,控制流将移至 finally 块,然后程序的其余部分将继续执行。

实施

输出

 
Inside the try block and try block fully executed
The finally block is usually executed
Outside of the try-catch clause