Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 months ago.
The community reviewed whether to reopen this question 4 months ago and left it closed:
Original close reason(s) were not resolved
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(4)
catch
将捕获您的异常(以及发生的任何其他异常)。话虽如此,我尽量避免编写这样的代码。就我个人而言,我认为没有理由对同一范围内抛出的异常进行异常处理(catch)。如果您可以在方法中处理错误 - 将异常处理(即:日志记录)也直接放在 try 块中。
在我看来,使用
catch
对于捕获try
块中的方法抛出的异常更有用。例如,如果您的// do stuff
部分碰巧调用了引发异常的方法,这会更有用。另外,我建议不要捕获每个异常 (
Exception e
),而是捕获您可以正确处理的特定类型的异常。唯一的例外是,如果您在 catch 中重新抛出异常,即:将其用于日志记录目的,但仍让它在调用堆栈中冒泡。The
catch
will catch your exception (and any other that occurs). That being said, I try to avoid writing code like this when possible.Personally, I see little reason to ever have exception handling (catch) for an exception thrown in the same scope. If you can handle your error in your method - put the exception handling (ie: logging) directly in the try block as well.
Using a
catch
is more useful, IMO, for catching exceptions thrown by methods within yourtry
block. This would be more useful, for example, if your// do stuff
section happened to call a method that raised an exception.Also, I recommend not catching every exception (
Exception e
), but rather the specific types of exceptions you can handle correctly. The one exception to this would be if you're rethrowing the exception within your catch - ie: using it for logging purposes but still letting it bubble up the call stack.是的,它会捕获从
Exception
派生的ApplicationException
。在大多数情况下,处理基本异常应该没问题,除非您需要记录或使用不同类型的异常执行某些操作...
Yes, it will catch
ApplicationException
as it derives fromException
.Handling the base exception should be fine in most cases unless you need to log or do something with a different type of exception...
另外,仅供参考,
ApplicationException
自 .NET 2.0 起作为派生例外已被弃用。它从来没有打算作为一个异常来单独抛出,所以你可能根本不应该使用它。Also, FYI,
ApplicationException
has been deprecated since .NET 2.0 as an exception to derive from. It was never intended as an exception to throw on its own, so you probably shouldn't use it at all.是的,catch 会捕获您的 ApplicationException ,是的,这是糟糕的编码风格。作为一个好的一般规则,仅捕获特定的异常以及您将要处理的异常,例如修复应用程序状态。
Yes the catch would catch your ApplicationException and yes is is poor coding style. As a good general rule only catch specific exception and those that you are going to do something with, like fixing up application state.