溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C#?System.TypeInitializationException異常如何處理

發(fā)布時間:2023-02-27 09:18:40 來源:億速云 閱讀:143 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“C# System.TypeInitializationException異常如何處理”的相關(guān)知識,小編通過實(shí)際案例向大家展示操作過程,操作方法簡單快捷,實(shí)用性強(qiáng),希望這篇“C# System.TypeInitializationException異常如何處理”文章能幫助大家解決問題。

C# System.TypeInitializationException 異常處理

備忘

C#?System.TypeInitializationException異常如何處理

問題在這

C#?System.TypeInitializationException異常如何處理

這種錯誤大多是聲明的類里面初始字段賦值出了問題

比如 在類里面生命了一個 太大的數(shù)組,超出了最大內(nèi)存限制就會出錯

C#?System.TypeInitializationException異常如何處理

修改下就OK了

C#基礎(chǔ)--錯誤和異常

異常類

在c#中,當(dāng)出現(xiàn)某個特殊的異常錯誤條件時,就會創(chuàng)建(或拋出)一個異常對象。這個對象包含有助于跟蹤問 題的信息。我們可以創(chuàng)建自己的異常類,但.NET提供了許多預(yù)定義的異常類,多到這里不可能 提供詳盡的列表。

列舉幾個常見異常:

  • StackOverflowException—如果分配給棧的內(nèi)存區(qū)域己滿,就會拋出這個異常。

  • EndOfStreamException—這個異常通常是因?yàn)樽x到文件末尾而拋出的。

  • OverflowException—如果要在checked上下文中把包含值-40的int類型數(shù)據(jù)強(qiáng)制轉(zhuǎn)換為uint數(shù)據(jù),就會拋出這個異常。

捕獲異常

  • try塊包含的代碼組成了程序的正常操作部分,但這部分程序可能遇到某些嚴(yán)重的錯誤。

  • catch塊包含的代碼處理各種錯誤情況,這些錯誤是執(zhí)行try塊中的代碼時遇到的。這個塊還可以用于記 錄錯誤。

  • finally塊包含的代碼清理資源或執(zhí)行通常要在try塊或catch塊末尾執(zhí)行的其他操作。無論是否拋出異常,都會執(zhí)行finally塊,理解這一點(diǎn)非常重要。因?yàn)閒inally塊包含了應(yīng)總是執(zhí)行的清理代碼,如果 在finally塊中放置了return語句,編譯器就會標(biāo)記一個錯誤。

下面的步驟說明了這些塊是如何組合在一起捕獲錯誤情況的:

(1) 執(zhí)行的程序流進(jìn)入try塊。

(2) 如果在try塊中沒有錯誤發(fā)生,在塊中就會正常執(zhí)行操作。當(dāng)程序流到達(dá)try塊末尾后,如果存在一個finally塊,程序流就會自動SA finally塊(第(5)步)。但如果在try塊中程序流檢測到一個錯誤,程序流就會跳轉(zhuǎn) 到catch塊(第⑶步)。

(3) 在catch塊中處理錯誤。

(4) 在catch塊執(zhí)行完后,如果存在一個finally塊,程序流就會自動進(jìn)入finally塊:

(5) 執(zhí)行finally塊(如果存在)。

try
{
    
}
catch (Exception ex)
{
    
}
finally
{
    
}

異常性能

異常處理具有性能含義。在常見的情況下,不應(yīng)該使用異常處理錯誤。例如,將字符串轉(zhuǎn)換為數(shù)字時,可 以使用int類型的Paree方法。如果傳遞給此方法的字符串不能轉(zhuǎn)換為數(shù)字,此方法拋FormatException異常;如果可以轉(zhuǎn)換一個數(shù)字,但它不能放在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方法通常只用于在字符串中傳遞數(shù)字而接收不到數(shù)字是異常的,那么可以這樣編寫它。 但是,如果在程序流的正常情況下,期望的字符串不能轉(zhuǎn)換時,可以使用TryParse方法。如果字符串不能轉(zhuǎn)換 為數(shù)字,此方法不會拋出異常。相反,如果解析成功,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");
    }
}

實(shí)現(xiàn)多個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時執(zhí)行。捕獲不同的異常類型時,可以有行為不同的catch塊。在某些情況下,catch塊基于異常的內(nèi)容執(zhí)行不同的操作。

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();
        }
    }
}

關(guān)于“C# System.TypeInitializationException異常如何處理”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識,可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會為大家更新不同的知識點(diǎn)。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI