在具有 try-catch-finally 的语言中,是否可以以某种方式对所有异常处理程序执行操作?
是否有任何语言支持类似下面的构造,或者是否有一个使用无处不在的 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 等中有这样的支持吗?
Is there any language that supports something like the below construct, or is there a good way to achieve this using the ubiquitous 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.
}
I understand this depends on the particular language, but is there some such support in Java, C#, C++, PHP etc?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在主程序或高级方法中放置“全局”try/catch。这捕获了其他地方未捕获的所有异常。
然后,在从属 try/catch 子句中,只需以通常的方式处理异常,然后重新抛出。重新抛出的异常将冒泡到主 try/catch 并被记录。
Put a "global" try/catch in your main program or high-level method. This catches all exceptions that are not caught elsewhere.
Then, in your subordinate try/catch clauses, just handle your exceptions in the usual way, and then rethrow. The rethrown exception will bubble up to your main try/catch and be logged.
我不这么认为,因为您描述的行为可以很容易地建模为:
I don't think so as the behaviour you describe can be easily modelled as:
您可以使用 C# 轻松实现这一点。一种简单的方法是将异常保存在 catch 块中,然后在 finally 块中记录异常对象是否不为 null。
You can easily accomplish that in C#. A simple way would be to save the exception in your catch blocks, then in your finally block, log if the exception object is not null.
Visual Basic 有一个可用于此目的的构造。从[几乎]永远不会执行失败的意义上来说,这并不是真正的“最终”,但是当您只想记录正在处理的异常并且可以访问其中的异常对象时,它会支持这种情况共享代码。您还可以灵活地在单个异常类型代码之前或之后执行共享代码。
Visual Basic has a construct that can be used for this. This isn't really "finally" in the sense of [almost] never failing to execute, but it'll support the case when you only want to log the exceptions that you're handling, and you have access to the exception object within the shared code. You've also got the flexibility of having the shared code execute before or after the individual exception type code.
像这样的事情,只要语言有
throw
不带参数来重新抛出捕获的异常:那就是如果您想在异常发生时记录 - 如果您只想记录您实际捕获的异常,那么不要将“执行操作”放在finally块中,只需将其放在内部try-catch结束之后即可。
Something like this, as long as the language has
throw
with no parameters to rethrow a caught exception:That's if you want to log whenever an exception occurs - if you only want to log the ones you actually catch, then don't put the "Perform action" in a finally block, just put it after the end of the inner try-catch.