抛出新的异常VS Catch块 [英] throw new Exception vs Catch block

查看:136
本文介绍了抛出新的异常VS Catch块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有之间的行为差​​异:

Is there any behavioural difference between:

if (s == null) // s is a string
{
 throw new NullReferenceException();
}

try
{
  Console.Writeline(s);
}


catch (NullReferenceException Ex)
{ // logic in here 
}

这两个抛出空对象的例外,如果s为null。第一个例子是更可读的,因为它显示的确切位置发生错误(异常位毗邻,这将导致异常的行)。

Both throw exceptions of null object, if s is null. The first example is more readable as it shows exactly where the error occurs (the exception bit is right next to the line which will cause the exception).

我已经看到了这一点通过各种技能水平的不同编码器的编码风格上的各种博客很多,但为什么不通过检查s不是空从不断被提出执行主逻辑,从而节省例外?是否有一个缺点这种做法?

I have seen this coding style a lot on various blogs by various coders of all sorts of skill levels, but why not just perform the main logic by checking if s is not null and thus save the exception from ever being raised? Is there a downside to this approach?

感谢

推荐答案

没有, Console.WriteLine(空)不会抛出异常。它只是将打印什么去。现在,假设你的意思是这样的:

No, Console.WriteLine(null) won't throw an exception. It will just print nothing out. Now assuming you meant something like:

Console.WriteLine(s.Length);



话很有道理...你应该使用第一种形式。当你无法与当前的信息提前预测的时间他们异常应该发生。如果你能很容易地制定出的东西是错的,这是没有意义的尝试是注定要失败的操作。它导致代码是很难理解和执行得很差。

then it makes sense... and you should use the first form. Exceptions should occur when you can't predict them ahead of time with your current information. If you can easily work out that something's wrong, it makes no sense to try an operation which is bound to fail. It leads to code which is harder to understand and performs worse.

所以的NullReferenceException ArgumentNullException 等不应该被捕获除非他们由于讨厌的API,它有时抛出,你可以处理异常,但真不该被摆在首位抛出。这就是为什么在代码契约,对于失败的合同的默认行为是抛出你的异常不能的赶明确,比其他通过捕捉的所有的(通常是在堆栈的顶部某处)

So NullReferenceException, ArgumentNullException and the like shouldn't be caught unless they're due to a nasty API which sometimes throws exceptions which you can handle, but which shouldn't really be being thrown in the first place. This is why in Code Contracts, the default behaviour for a failed contract is to throw an exception which you can't catch explicitly, other than by catching everything (which is typically somewhere at the top of the stack).

这篇关于抛出新的异常VS Catch块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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