异常处理.在C#中 [英] Exception handling. in c#

查看:125
本文介绍了异常处理.在C#中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这2个有什么区别!

what is the difference between these 2!

try
{
dosomething();
}
catch
{
throw;
}




上下之间的差异.




difference between above and below one.

try
{
dosomething();
}
catch(System.Exception ex)
{
throw ex;
}

推荐答案

查看以下代码项目文章:

.NET中的异常处理最佳实践 [
Look at this codeproject article:

Exception Handling Best Practices in .NET[^]


在实践中,两种情况完全相同.而且,它们是完全冗余的,仅浪费CPU时间.

请在我对avigodse的(不正确)答案的评论中找到更详细的解释.
现在,此答案已得到改善. Avigodse可能正确理解了异常的工作原理,只是需要额外的解释.声明ex是Question的最后一个代码示例,建议在重新抛出异常之前可以添加一些处理.在未完成之前,两个样本都执行相同且完全冗余的操作.请参阅我对提到的答案的评论.

重要的是不要阻止异常传播到堆栈,因此在许多情况下应重新抛出异常.如果需要特殊处理,则应使用特殊类型的异常(从System.Exception派生的类型).此类型是报告所有异常和/或记录它们或创建异常转储以报告CodeProject问题的最佳方法:-).

请参阅我有关使用异常的其他说明:

我如何制作滚动条到达底部时将停止的循环 [当我运行应用程序时,异常是捕获了如何处理此问题? [
In practice both cases do exactly the same. Also, they are completely redundant, only waste CPU time.

Please find more detailed explanation in my comment to the (incorrect) Answer by avigodse.
Now this answer is improved. Avigodse probably understands correctly how exception works, only it requires additional explanation. Declaration ex is the last code sample of the Question suggests some processing can be added before re-throwing exception. Until it is not done, both samples do the same and completely redundant. See my comment to the mentioned Answer.

It''s very important not to block propagation of exceptions up to stack, so in many cases the exception should be re-thrown. If special processing is needed, the specialized type of exception should be used (of a type derived from System.Exception). This type is the best to report all exceptions and/or log them or created exception dump to report problems for CodeProject Questions :-).

See my additional instructions on using exception:

How do i make a loop that will stop when a scrollbar reaches the bottom[^]
When i run an application an exception is caught how to handle this?[^]

I tried to list best practices.

—SA


希望 Link1 [^ ]和 Link2 [ ^ ]可能会为您提供帮助.
Hope Link1[^] and Link2[^] might help you.


这篇关于异常处理.在C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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