捕获一般异常真的那么糟糕吗? [英] Is it really that bad to catch a general exception?

查看:28
本文介绍了捕获一般异常真的那么糟糕吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 FXCop 分析一些遗留代码时,我想到在 try 块中捕获一般异常错误真的很糟糕,或者您是否应该寻找特定的异常.请在明信片上思考.

Whilst analysing some legacy code with FXCop, it occurred to me is it really that bad to catch a general exception error within a try block or should you be looking for a specific exception. Thoughts on a postcard please.

推荐答案

显然,这是唯一真正答案是视情况而定"的问题之一.

Obviously this is one of those questions where the only real answer is "it depends."

它主要取决于您在哪里捕获异常.一般来说,库在捕获异常方面应该更加保守,而在程序的顶层(例如,在您的 main 方法中或在控制器中的操作方法的顶部等)您可以更加自由地捕捉到什么.

The main thing it depends on is where your are catching the exception. In general libraries should be more conservative with catching exceptions whereas at the top level of your program (e.g. in your main method or in the top of the action method in a controller, etc) you can be more liberal with what you catch.

这样做的原因是,例如您不想捕获库中的所有异常,因为您可能会掩盖与您的库无关的问题,例如您确实希望冒泡的OutOfMemoryException",以便通知用户等.另一方面手,如果您正在谈论在 main() 方法中捕获异常,该方法捕获异常,显示它然后退出......好吧,在这里捕获几乎所有异常可能是安全的.

The reason for this is that e.g. you don't want to catch all exceptions in a library because you may mask problems that have nothing to do with your library, like "OutOfMemoryException" which you really would prefer bubbles up so that the user can be notified, etc. On the other hand, if you are talking about catching exceptions inside your main() method which catches the exception, displays it and then exits... well, it's probably safe to catch just about any exception here.

关于捕获所有异常的最重要的规则是,你不应该只是默默地吞下所有异常......例如在 Java 中是这样的:

The most important rule about catching all exceptions is that you should never just swallow all exceptions silently... e.g. something like this in Java:

try { 
    something(); 
} catch (Exception ex) {}

或 Python 中的这个:

or this in Python:

try:
    something()
except:
    pass

因为这些可能是最难追踪的一些问题.

Because these can be some of the hardest issues to track down.

一个好的经验法则是,您应该只捕获您自己可以正确处理的异常.如果你不能完全处理异常,那么你应该让它冒泡给有能力的人.

A good rule of thumb is that you should only catch exceptions that you can properly deal with yourself. If you cannot handle the exception completely then you should let it bubble up to someone who can.

这篇关于捕获一般异常真的那么糟糕吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆