是否有任何语言支持类似下面的构造,或者是否有使用无处不在的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等语言中有这样的支持吗?
发布于 2011-04-28 22:30:43
将“全局”try/catch放在主程序或高级方法中。这将捕获在其他地方未捕获的所有异常。
try
{
     // Main method, or higher level method call
} 
catch (Exception ex)
{
     // Log exception here
}然后,在从属的try/catch子句中,只需以通常的方式处理异常,然后重新抛出。重新抛出的异常将冒泡到您的主try/catch并被记录下来。
try
{
     // Do your thing
}
catch(SomeException ex)
{
     // Handle exception here
     // rethrow exception to logging handler 
     throw;
}发布于 2011-04-28 21:42:57
我不这么认为,因为你所描述的行为可以很容易地建模为:
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-28 21:44:55
您可以在C#中轻松实现这一点。一种简单的方法是将异常保存在catch块中,如果exception对象不为空,则在finally块中记录该异常。
Exception ex;
try
{
}
catch (ExceptionType1 type1)
{
    ex = type1;
}
catch (ExceptionType2 type2)
{
    ex = type2;
}
finally
{
    if (ex != null)
    {
        //Log
    }
}https://stackoverflow.com/questions/5819503
复制相似问题