异常处理C#

本文讨论了C#中异常处理的重要性,指出未处理的异常会导致系统返回500错误,不利于调试和用户体验。建议在代码中适当地使用try-catch块,针对不同类型的异常采取不同策略,如记录日志或通知用户。同时,提倡在UI应用中向用户显示错误,服务或控制台应用中记录到文件,并在可能出现异常的代码段中使用try-catch。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在项目中,后端接口如果不进行异常处理那遇到所有问题(后端中的问题)都会自动被处理成顶级异常并返回状态码500(server internal error),这样无论是Debug还是前端提示用户都不清楚。

异常处理的好处

对于整个代码逻辑,如果没有在底层进行异常处理,异常就会一级一级往上抛,直到最外层的。

如果在一个大的系统或服务代码中,不能因为一个小bug就导致整个功能停止。可以预见到的局部且不会影响后续代码逻辑的异常就在本地接受并进行处理,将出现的异常记录到log中,仅有coder可以在日志中进行查看看。如果是会影响到后续代码执行或者是严重的错误,就直接在local让程序停下来没必要继续执行了。

建议的做法 

https://stackoverflow.com/questions/14973642/how-using-try-catch-for-exception-handling-is-best-practice

  • To catch all unhandled exceptions by hooking to the Application.ThreadException event, then decide :

    • For a UI application: to pop it to the user with an apology message (winforms)
    • For a Service or a Console application: log it to a file (service or console)

Then I always enclose every piece of code that is run externally in try/catch :

  • All events fired by the Winforms infrastructure (Load, Click, SelectedChanged...)
  • All events fired by third party components

Then I enclose in 'try/catch'

  • All the operations that I know might not work all the time (IO operations, calculations with a potential zero division...). In such a case, I throw a new ApplicationException("custom message", innerException) to keep track of what really happened

Additionally, I try my best to sort exceptions correctly. There are exceptions which:

  • need to be shown to the user immediately
  • require some extra processing to put things together when they happen to avoid cascading problems (ie: put .EndUpdate in the finally section during a TreeView fill)
  • the user does not care, but it is important to know what happened. So I always log them:

    • In the event log
    • or in a .log file on the disk

It is a good practice to design some static methods to handle exceptions in the application top level error handlers.

I also force myself to try to:

  • Remember ALL exceptions are bubbled up to the top level. It is not necessary to put exception handlers everywhere.
  • Reusable or deep called functions does not need to display or log exceptions : they are either bubbled up automatically or rethrown with some custom messages in my exception handlers.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值