首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >try-finally和try-catch之间的区别

try-finally和try-catch之间的区别
EN

Stack Overflow用户
提问于 2010-05-18 14:15:14
回答 11查看 110.2K关注 0票数 99

两者的区别是什么

代码语言:javascript
复制
try {
    fooBar();
} finally {
    barFoo();
}

代码语言:javascript
复制
try {
  fooBar();
} catch(Throwable throwable) {
    barFoo(throwable); // Does something with throwable, logs it, or handles it.
}

我更喜欢第二个版本,因为它让我可以访问Throwable。这两种变体之间是否存在逻辑上的差异或首选约定?

另外,有没有办法访问finally子句中的异常?

EN

回答 11

Stack Overflow用户

回答已采纳

发布于 2010-05-18 14:17:06

这是两件不同的事情:

  • 仅当try块中引发异常时才执行catch块。
  • 无论是否引发异常,finally块总是在try(-catch)块之后执行。

在您的示例中,您还没有展示第三种可能的构造:

代码语言:javascript
复制
try {
    // try to execute this statements...
}
catch( SpecificException e ) {
    // if a specific exception was thrown, handle it here
}
// ... more catches for specific exceptions can come here
catch( Exception e ) {
    // if a more general exception was thrown, handle it here
}
finally {
    // here you can clean things up afterwards
}

而且,就像@codeca在他的评论中所说的,没有办法访问finally块中的异常,因为即使没有异常,finally块也会被执行。

当然,您可以在块外部声明一个保存异常的变量,并在catch块内赋值。之后,您可以在finally块中访问此变量。

代码语言:javascript
复制
Throwable throwable = null;
try {
    // do some stuff
}
catch( Throwable e ) {
    throwable = e;
}
finally {
    if( throwable != null ) {
        // handle it
    }
}
票数 128
EN

Stack Overflow用户

发布于 2010-05-18 14:17:50

这些不是变体,它们是根本不同的东西。始终执行finally,仅在发生异常时执行catch

票数 11
EN

Stack Overflow用户

发布于 2010-05-18 23:12:13

Finally和catch块有很大的不同:

  • 在catch块中,您可以响应抛出的异常。仅当存在未处理的异常,并且类型与catch块的parameter.
  • Finally中指定的类型的子类匹配时,才会执行此块。无论是否引发异常,都将始终在 catch块之后执行此块。

所以

代码语言:javascript
复制
try {
  //some code
}
catch (ExceptionA) {
  // Only gets executed if ExceptionA 
  // was thrown in try block
}
catch (ExceptionB) {
  // Only executed if ExceptionB was thrown in try 
  // and not handled by first catch block
}

不同于

代码语言:javascript
复制
try {
  //some code
}
finally {
  // Gets executed whether or not 
  // an exception was thrown in try block
}

重要的是。

如果定义try块,则必须定义

  1. one finally block,or
  2. 一个或多个catch block,或
  3. 一个或多个catch block和一个finally

所以下面的代码也是有效的:

代码语言:javascript
复制
try {
  //some code
}
catch (ExceptionA) {
  // Only gets executed if 
  // ExceptionA was thrown in try block
}
catch (ExceptionB) {
  // Only executed if ExceptionB was thrown in 
  // try and not handled by first catch block
}
//even more catch blocks
finally {
  // Gets executed whether or not an 
  // exception was thrown in try block
}
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2854910

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档