日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C#?System.TypeInitializationException?異常處理方案_C#教程

作者:yangzm996 ? 更新時間: 2023-06-18 編程語言

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

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新