Java 异常处理中的流控制

Java 异常处理中的流控制,java,exception-handling,try-catch-finally,Java,Exception Handling,Try Catch Finally,我对Java相当陌生,无法理解try-catch-finally块中的控制流。每当在catch块中捕获异常时,catch块之后的代码也会被执行,无论我是否将其放在finally块中。那么finally block有什么用呢 class Excp { public static void main(String args[]) { int a,b,c; try { a=0; b=10; c=b/a; System.out.println("This line

我对Java相当陌生,无法理解try-catch-finally块中的控制流。每当在catch块中捕获异常时,catch块之后的代码也会被执行,无论我是否将其放在finally块中。那么finally block有什么用呢

class Excp
{
 public static void main(String args[])
 {
  int a,b,c;
  try
  {
   a=0;
   b=10;
   c=b/a;
   System.out.println("This line will not be executed");
  }
  catch(ArithmeticException e)
  {
   System.out.println("Divided by zero"); 
  }
  System.out.println("After exception is handled");
 }
}

如果我将最后一条print语句放在finally块中,则没有区别。

如果在
try/catch
块中发生另一个异常(未经代码处理),则会产生区别

如果没有
finally
,最后一行将无法执行。使用
finally
,无论发生什么情况,都会执行代码


这对于执行垃圾收集器无法执行的清理任务特别有用:系统资源、数据库锁定、文件删除等。

如果从
catch
块抛出异常,或者如果从
try
块抛出不同的异常,那么
finally
块也将执行

示例:

try {
  int a=5;
  int b=0;
  int c=a/b;
catch (NullPointerException e) {
  // won't reach here
} finally {
  // will reach here
}
您还可以完全省略catch块,并且仍然保证将执行finally块:

try {
  int a=5;
  int b=0;
  int c=a/b;
} finally {
  // will reach here
}
考虑这一点:

try {
    a=0;
    b=10;
    c=b/a;
    System.out.println("This line will not be executed");
}
catch(ArithmeticException e){
    throw new RuntimeException("Stuff went wrong", e); 
}
System.out.println("This line will also not be executed");

即使在
try
catch
中存在
返回
或未处理的异常,finally块中的代码始终执行。
这是解释,这是发现了一个非常简单的谷歌搜索请使用google。

即使在函数返回后,也可以使用finally块执行

e、 g


将返回false

try
中抛出
newruntimeexception()
,您会注意到catch块之后的代码没有执行。然后添加一个finally块。您可以使用
finally
块将程序设置为任何异常发生后可以使用的状态。finally块中的代码始终执行,即使在
try
catch
中存在
return
或未处理的异常。这是通过一个非常简单的谷歌搜索找到的。请使用谷歌。
public boolean doSmth() {
  try {
   return true;
  }
  finally {
    return false;
  }
}