赶上(例外),赶上()和刚捕捞的区别 [英] Difference between catch(Exception), catch() and just catch

查看:151
本文介绍了赶上(例外),赶上()和刚捕捞的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如果我可以放心地写赶上()只能捕获所有System.Exception的类型。还是我一直坚持赶上(异常)来实现这一点。我知道其他的异常类型(如InvalidCastException的),我必须指定类型为捕捉(InvalidCastException的)。换句话说,我问如果发生以下code样品是相同的。

I want to know if I can safely write catch() only to catch all System.Exception types. Or do I've to stick to catch(Exception) to accomplish this. I know for other exception types (e.g. InvalidCastException), I have to specify the type as catch(InvalidCastException). In other words, I'm asking if the following code samples are the same.

这...

try
{
    //do something
}
catch(Exception)
{
    //handle exception
}

这...

try
{
    //do something
}
catch() //Causes compile time error "A class type expected"
{
    //handle exception
}

这...

try
{
    //do something
}
catch
{
    //handle exception
}

更新:有我的问题的错误。 赶上()在C#中是不允许的。

update: There was an error in my question. catch() is not allowed in c#.

推荐答案

在一个完美的世界里,你不应该使用赶上(例外)(单独)在所有的,因为你永远不应该赶上一般异常例外。你总是应该抓住更具体的例外(比如 InvalidOperationException异常 ...等)。

In a perfect world, you shouldn't use catch(Exception) nor catch (alone) at all, because you should never catch the generic Exception exception. You always should catch more specific exceptions (for instance InvalidOperationException...etc.).

在一个真实的世界,无论是赶上(例外)(单独)是等价的。我推荐使用赶上(例外前)当你打算重用异常变量而已,而在捕获(单独)其他案件。风格为第二个用例只是一个问题,但如果个人觉得更简单。

In a real world, both catch(Exception) and catch (alone) are equivalent. I recommend using catch(Exception ex) when you plan to reuse the exception variable only, and catch (alone) in other cases. Just a matter of style for the second use case, but if personally find it more simple.

什么是真正重要的(即使它是你的问题的范围)的是您从来不写了下面这段code

What's really important (even if it's out of the scope of your question) is that you never write the following piece of code:

try
{
}
catch (SpecificException ex)
{
    throw ex;
}

这将重置堆栈跟踪到抛出点。在另一方面:

This would reset the stack trace to the point of the throw. In the other hand:

try
{
}
catch (SpecificException)
{
    throw;
}

保持原有的堆栈跟踪。

maintain the original stack trace.

这篇关于赶上(例外),赶上()和刚捕捞的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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