網站首頁 編程語言 正文
C# System.TypeInitializationException 異常處理
備忘
問題在這
這種錯誤大多是聲明的類里面初始字段賦值出了問題
比如 在類里面生命了一個 太大的數組,超出了最大內存限制就會出錯
修改下就OK了
C#基礎--錯誤和異常
異常類
在c#中,當出現某個特殊的異常錯誤條件時,就會創建(或拋出)一個異常對象。這個對象包含有助于跟蹤問 題的信息。我們可以創建自己的異常類,但.NET提供了許多預定義的異常類,多到這里不可能 提供詳盡的列表。
列舉幾個常見異常:
-
StackOverflowException
—如果分配給棧的內存區域己滿,就會拋出這個異常。 -
EndOfStreamException
—這個異常通常是因為讀到文件末尾而拋出的。 -
OverflowException
—如果要在checked上下文中把包含值-40的int類型數據強制轉換為uint數據,就會拋出這個異常。
捕獲異常
-
try
塊包含的代碼組成了程序的正常操作部分,但這部分程序可能遇到某些嚴重的錯誤。 -
catch
塊包含的代碼處理各種錯誤情況,這些錯誤是執行try塊中的代碼時遇到的。這個塊還可以用于記 錄錯誤。 -
finally
塊包含的代碼清理資源或執行通常要在try塊或catch塊末尾執行的其他操作。無論是否拋出異常,都會執行finally塊,理解這一點非常重要。因為finally塊包含了應總是執行的清理代碼,如果 在finally塊中放置了return語句,編譯器就會標記一個錯誤。
下面的步驟說明了這些塊是如何組合在一起捕獲錯誤情況的:
(1) 執行的程序流進入try塊。
(2) 如果在try塊中沒有錯誤發生,在塊中就會正常執行操作。當程序流到達try塊末尾后,如果存在一個finally塊,程序流就會自動SA finally塊(第(5)步)。但如果在try塊中程序流檢測到一個錯誤,程序流就會跳轉 到catch塊(第⑶步)。
(3) 在catch塊中處理錯誤。
(4) 在catch塊執行完后,如果存在一個finally塊,程序流就會自動進入finally塊:
(5) 執行finally塊(如果存在)。
try { } catch (Exception ex) { } finally { }
異常性能
異常處理具有性能含義。在常見的情況下,不應該使用異常處理錯誤。例如,將字符串轉換為數字時,可 以使用int類型的Paree方法。如果傳遞給此方法的字符串不能轉換為數字,此方法拋FormatException異常;如果可以轉換一個數字,但它不能放在int類型中,則拋出OverflowException異常:
static void NumberDemol(string n) { ?? ?if (n is null) throw new ArgumentNullException(nameof(n));? ?? ?try ?? ?{ ?? ??? ?int i = int.Parse(n); ?? ??? ?Console.WriteLine($"converted: {i}"); ?? ?} ?? ?catch (FormatException ex) ?? ?{ ?? ??? ?Console.WriteLine(ex.Message); ?? ?} ?? ?catch (OverflowException ex) ?? ?{ ?? ??? ?Console.WriteLine(ex.Message); ?? ?} }
如果NumberDemol方法通常只用于在字符串中傳遞數字而接收不到數字是異常的,那么可以這樣編寫它。 但是,如果在程序流的正常情況下,期望的字符串不能轉換時,可以使用TryParse方法。如果字符串不能轉換 為數字,此方法不會拋出異常。相反,如果解析成功,TryParse返回true;如果解析失敗,則返回felse:
static void NumberDemo2(string n) { ?? ?if (n is null) throw new ArgumentNullException(nameof(n));? ?? ?if (int.TryParse(n, ? out int result)) ?? ?{ ?? ??? ?Console. WriteLine ($"converted {result}"); ?? ?} ?? ?else ?? ?{ ?? ??? ?Console.WriteLine("not a number"); ?? ?} }
實現多個catch塊
class Program { ? ? static void Main() ? ? { ? ? ? ? while (true) ? ? ? ? { ? ? ? ? ? ? try ? ? ? ? ? ? { ? ? ? ? ? ? ? ? string userInput; ? ? ? ? ? ? ? ? Console.Write("Input a number between 0 and 5 or just hit return to exit)> "); ? ? ? ? ? ? ? ? userInput = Console.ReadLine(); ? ? ? ? ? ? ? ? if (string.IsNullOrEmpty(userInput)) ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? break; ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? int index = Convert.ToInt32(userInput); ? ? ? ? ? ? ? ? if (index < 0 || index > 5) ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? throw new IndexOutOfRangeException($"You typed in {userInput}"); ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? Console.WriteLine($"Your number was {index}"); ? ? ? ? ? ? } ? ? ? ? ? ? catch (IndexOutOfRangeException ex) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? Console.WriteLine($"Exception: Number should be between 0 and 5. {ex.Message}"); ? ? ? ? ? ? } ? ? ? ? ? ? catch (Exception ex) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? Console.WriteLine($"An exception was thrown. Message was: {ex.Message}"); ? ? ? ? ? ? } ? ? ? ? ? ? finally ? ? ? ? ? ? { ? ? ? ? ? ? ? ? Console.WriteLine("Thank you\n"); ? ? ? ? ? ? } ? ? ? ? } ? ? } }
異常過濾器
自從C# 6開始就支持異常過濾器。catck塊僅在過濾器返回true時執行。捕獲不同的異常類型時,可以有行為不同的catch塊。在某些情況下,catch塊基于異常的內容執行不同的操作。
class Program { ? ? static void Main() ? ? { ? ? ? ? try ? ? ? ? { ? ? ? ? ? ? ThrowWithErrorCode(405); ? ? ? ? } ? ? ? ? catch (MyCustomException ex) when (ex.ErrorCode == 405) ? ? ? ? { ? ? ? ? ? ? Console.WriteLine($"Exception caught with filter {ex.Message} and {ex.ErrorCode}"); ? ? ? ? } ? ? ? ? catch (MyCustomException ex) ? ? ? ? { ? ? ? ? ? ? Console.WriteLine($"Exception caught {ex.Message} and {ex.ErrorCode}"); ? ? ? ? } ? ? ? ? Console.ReadLine(); ? ? } ? ? public static void ThrowWithErrorCode(int code) ? ? { ? ? ? ? throw new MyCustomException("Error in Foo") { ErrorCode = code }; ? ? } }
自定義異常
這個示例稱為SolicitColdCall,它包 含兩個嵌套的try塊,說明了如何定義自定義異常類,再從try塊中拋出另一個異常。
public class ColdCallFileFormatException : Exception { public ColdCallFileFormatException(string message) : base(message) { } public ColdCallFileFormatException(string message, Exception innerException) : base(message, innerException) { } } public class SalesSpyFoundException : Exception { public SalesSpyFoundException(string spyName) : base($"Sales spy found, with name {spyName}") { } public SalesSpyFoundException(string spyName, Exception innerException) : base($"Sales spy found with name {spyName}", innerException) { } } public class UnexpectedException : Exception { public UnexpectedException(string message) : base(message) { } public UnexpectedException(string message, Exception innerException) : base(message, innerException) { } } public class ColdCallFileReader : IDisposable { private FileStream _fs; private StreamReader _sr; private uint _nPeopleToRing; private bool _isDisposed = false; private bool _isOpen = false; public void Open(string fileName) { if (_isDisposed) { throw new ObjectDisposedException("peopleToRing"); } _fs = new FileStream(fileName, FileMode.Open); _sr = new StreamReader(_fs); try { string firstLine = _sr.ReadLine(); _nPeopleToRing = uint.Parse(firstLine); _isOpen = true; } catch (FormatException ex) { throw new ColdCallFileFormatException( $"First line isn\'t an integer {ex}"); } } public void ProcessNextPerson() { if (_isDisposed) { throw new ObjectDisposedException("peopleToRing"); } if (!_isOpen) { throw new UnexpectedException( "Attempted to access coldcall file that is not open"); } try { string name = _sr.ReadLine(); if (name == null) { throw new ColdCallFileFormatException("Not enough names"); } if (name[0] == 'B') { throw new SalesSpyFoundException(name); } Console.WriteLine(name); } catch (SalesSpyFoundException ex) { Console.WriteLine(ex.Message); } finally { } } public uint NPeopleToRing { get { if (_isDisposed) { throw new ObjectDisposedException("peopleToRing"); } if (!_isOpen) { throw new UnexpectedException( "Attempted to access cold–call file that is not open"); } return _nPeopleToRing; } } public void Dispose() { if (_isDisposed) { return; } _isDisposed = true; _isOpen = false; _fs?.Dispose(); _fs = null; } } class Program { static void Main() { Console.Write("Please type in the name of the file " + "containing the names of the people to be cold called > "); string fileName = Console.ReadLine(); ColdCallFileReaderLoop1(fileName); Console.WriteLine(); ColdCallFileReaderLoop2(fileName); Console.WriteLine(); Console.ReadLine(); } private static void ColdCallFileReaderLoop2(string fileName) { using (var peopleToRing = new ColdCallFileReader()) { try { peopleToRing.Open(fileName); for (int i = 0; i < peopleToRing.NPeopleToRing; i++) { peopleToRing.ProcessNextPerson(); } Console.WriteLine("All callers processed correctly"); } catch (FileNotFoundException) { Console.WriteLine($"The file {fileName} does not exist"); } catch (ColdCallFileFormatException ex) { Console.WriteLine($"The file {fileName} appears to have been corrupted"); Console.WriteLine($"Details of problem are: {ex.Message}"); if (ex.InnerException != null) { Console.WriteLine($"Inner exception was: {ex.InnerException.Message}"); } } catch (Exception ex) { Console.WriteLine($"Exception occurred:\n{ex.Message}"); } } } public static void ColdCallFileReaderLoop1(string fileName) { var peopleToRing = new ColdCallFileReader(); try { peopleToRing.Open(fileName); for (int i = 0; i < peopleToRing.NPeopleToRing; i++) { peopleToRing.ProcessNextPerson(); } Console.WriteLine("All callers processed correctly"); } catch (FileNotFoundException) { Console.WriteLine($"The file {fileName} does not exist"); } catch (ColdCallFileFormatException ex) { Console.WriteLine($"The file {fileName} appears to have been corrupted"); Console.WriteLine($"Details of problem are: {ex.Message}"); if (ex.InnerException != null) { Console.WriteLine($"Inner exception was: {ex.InnerException.Message}"); } } catch (Exception ex) { Console.WriteLine($"Exception occurred:\n{ex.Message}"); } finally { peopleToRing.Dispose(); } } }
總結
原文鏈接:https://blog.csdn.net/weixin_39448579/article/details/127422450
- 上一篇:沒有了
- 下一篇:沒有了
相關推薦
- 2024-01-31 linux下查看文件當下的所有文件的大小和查找大文件
- 2022-03-16 Oracle表空間管理和用戶管理介紹(oracle表空間與用戶的關系)
- 2022-07-15 Sql?Server存儲過程詳解_MsSql
- 2023-11-22 Linux在Ubuntu Linux下如何壓縮一個文件夾/文件
- 2022-03-14 flutter The argument type ‘String?‘ can‘t be assig
- 2022-03-20 詳解C語言對字符串處理函數的實現方法_C 語言
- 2022-10-14 sklearn.linear_model.Perceptron詳解
- 2024-03-25 Intellij IDEA 啟動tomcat報錯
- 欄目分類
-
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支