2

是否有任何语言支持类似以下构造的内容,或者是否有一种使用无处不在的 try-catch-finally 来实现此目的的好方法?

try
{

} catch(Exception1 e)
  { .... }
  catch(Exception2 e)
  { .... }
  catch-finally
   {
      //Perform action, such as logging
   }
  finally
   {
     //This always occurs but I only want to log when an exception occurs.
   }

我知道这取决于特定的语言,但是 Java、C#、C++、PHP 等是否有这样的支持?

4

5 回答 5

1

在您的主程序或高级方法中放置一个“全局”try/catch。这会捕获其他地方未捕获的所有异常。

try
{
     // Main method, or higher level method call
} 
catch (Exception ex)
{
     // Log exception here
}

然后,在您的下属 try/catch 子句中,以通常的方式处理您的异常,然后重新抛出。 重新抛出的异常将冒泡到您的主要尝试/捕获并被记录。

try
{
     // Do your thing
}
catch(SomeException ex)
{
     // Handle exception here

     // rethrow exception to logging handler 
     throw;
}
于 2011-04-28T14:30:43.050 回答
0

我不这么认为,因为您描述的行为可以很容易地建模为:

boolean success = false;

try {
  ...
  success = true;
} catch (Exception_1 e) {
  ...
}
...
} catch (Exception_N e) {
  ...
} finally {
  if (success) {
    // your "finally"
  } else {
    // your "catch-finally"
  }
}
于 2011-04-28T13:42:57.210 回答
0

您可以在 C# 中轻松实现这一点。一种简单的方法是将异常保存在 catch 块中,然后在 finally 块中记录异常对象是否为空。

Exception ex;

try
{

}
catch (ExceptionType1 type1)
{
    ex = type1;
}
catch (ExceptionType2 type2)
{
    ex = type2;
}
finally
{
    if (ex != null)
    {
        //Log
    }
}
于 2011-04-28T13:44:55.040 回答
0

Visual Basic 有一个可用于此的构造。从 [几乎] 永远不会执行失败的意义上来说,这并不是真正的“最终”,但是当您只想记录您正在处理的异常并且您可以访问其中的异常对象时,它将支持这种情况共享代码。您还可以灵活地在单个异常类型代码之前或之后执行共享代码。

Try
    ...
Catch ex As Exception When TypeOf(ex) Is Type1 OrElse TypeOf(ex) Is Type2
    ...
    If TypeOf(ex) Is Type1 Then
        ...
    ElseIf TypeOf(ex) Is Type2 Then
        ...
    End If
End Try
于 2011-04-28T13:54:02.570 回答
0

像这样,只要语言throw没有参数来重新抛出捕获的异常:

try
{

} catch(Everything) {
    try {
        throw;
    } catch (Exception1 e) {
        ....
    } catch (Exception2 e) {
        ....
    } finally {
        //Perform action, such as logging
    }
} finally {
        //This always occurs but I only want to log when an exception occurs.
}

那就是如果您想在发生异常时记录 - 如果您只想记录实际捕获的异常,则不要将“执行操作”放在 finally 块中,只需将其放在内部 try-catch 结束之后.

于 2011-04-28T14:23:09.980 回答