抓住一个普遍的例外真的那么糟糕吗? [英] Is it really that bad to catch a general exception?

查看:81
本文介绍了抓住一个普遍的例外真的那么糟糕吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用FXCop分析某些旧代码时,我想到的是,在try块中捕获一般的异常错误真的很不好,或者您是否正在寻找特定的异常。请在明信片上思考。

解决方案

很显然,这是唯一的答案是取决于的问题之一。 / p>

主要取决于您捕获异常的位置。通常,库应该在捕获异常时更加保守,而在程序的顶层(例如,在主方法中或在控制器的action方法的顶部等)中,您可以对捕获的内容更加自由。



其原因是例如您不想捕获库中的所有异常,因为您可能掩盖了与库无关的问题,例如 OutOfMemoryException,您确实更喜欢冒泡,以便可以通知用户,等等。另一方面,如果您正在谈论的是在main()方法中捕获异常的方法,该方法可以捕获异常,显示异常然后退出……那么,在这里捕获几乎所有异常都是安全的。



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

  try {
something();
} catch(异常例外){}

或在Python中这样:

 尝试:
something()
除外:
pass

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



一个好规则根据经验,您应该只捕获可以正确处理的异常。如果您不能完全处理异常,则应该让异常冒出来。


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