C# 中如何一次 catch 多个异常?
咨詢區
Michael Stum:
在項目開發中當拋出異常時,我會簡單的用 System.Exception,但這種會捕獲所有的異常,我不希望大一統,我只想捕獲我預知的幾個異常,然后在這里處理一些特定的業務邏輯。
目前我只能這么實現,代碼如下:
try {WebId?=?new?Guid(queryString["web"]); } catch?(FormatException) {WebId?=?Guid.Empty; } catch?(OverflowException) {WebId?=?Guid.Empty; }上面的兩種異常的處理邏輯是一致的,我但重復寫了 WebId = Guid.Empty; ,是否有辦法可以只寫一次呢?
回答區
Tamir Vered:
最簡單的方法就是在 catch 作用域中使用 if 語句, 但在 C#6.0 之后就不需要這么麻煩了,可以直接使用新特性 異常過濾器, 這種特性已經被 CLR 直接支持而不僅僅是 MSIL 上的一些小動作,修改后的代碼如下:
try {WebId?=?new?Guid(queryString["web"]); } catch?(Exception?exception)?when?(exception?is?FormatException?||?ex?is?OverflowException) {WebId?=?Guid.Empty; }上面的代碼僅僅會捕獲 InvalidDataException 和 ArgumentNullException 異常,當然你可以在 when 子句中弄出更復雜的語句,比如下面代碼:
static?int?a?=?8;...catch?(Exception?exception)?when?(exception?is?InvalidDataException?&&?a?==?8) {Console.WriteLine("Catch"); }值得注意的是:Exception Filters 和 catch 中寫 if 有著不同的語義,當第一個 Exception Filters 中的判斷條件不滿足或者在內部拋出了異常,代碼會繼續判斷下一個 Exception Filters ,參考代碼如下。
static?int?a?=?7; static?int?b?=?0;...try {throw?new?InvalidDataException(); } catch?(Exception?exception)?when?(exception?is?InvalidDataException?&&?a?/?b?==?2) {Console.WriteLine("Catch"); } catch?(Exception?exception)?when?(exception?is?InvalidDataException?||?exception?is?ArgumentException) {Console.WriteLine("General?catch"); }Output: General catch
如果 Exception Filter 有多個 true,那么只會命中第一個。
static?int?a?=?8; static?int?b?=?4;...try {throw?new?InvalidDataException(); } catch?(Exception?exception)?when?(exception?is?InvalidDataException?&&?a?/?b?==?2) {Console.WriteLine("Catch"); } catch?(Exception?exception)?when?(exception?is?InvalidDataException?||?exception?is?ArgumentException) {Console.WriteLine("General?catch"); }Output: Catch.
如果你觀察代碼的 IL,你會發現,Exception Filter 并不是多 if 判斷的語法糖,而是 MSIL 專門提供的 filter, endfilter ?關鍵詞法。
點評區
現代化的 C# 語法糖太多了,Michael Stum 大佬總結的很全面,學習了。
總結
以上是生活随笔為你收集整理的C# 中如何一次 catch 多个异常?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .NET 6新特性试用 | Contro
- 下一篇: C# WPF MVVM模式Prism框架