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

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

问题描述

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

解决方案

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

它主要取决于您在哪里捕获异常.通常,库在捕获异常方面应该更加保守,而在程序的顶层(例如,在主方法中或在控制器中的操作方法的顶部等),您可以对捕获的内容更加自由.

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

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

尝试{某物();} catch (Exception ex) {}

或者在 Python 中:

尝试:某物()除了:经过

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

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

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."

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.

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.

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) {}

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天全站免登陆