C# System.TypeInitializationException异常如何处理

这篇文章主要介绍“C# System.TypeInitializationException异常如何处理”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“C# System.TypeInitializationException异常如何处理”文章能帮助大家解决问题。

C# System.TypeInitializationException 异常处理

备忘

C# System.TypeInitializationException异常如何处理

问题在这

C# System.TypeInitializationException异常如何处理

这种错误大多是声明的类里面初始字段赋值出了问题

比如 在类里面生命了一个 太大的数组,超出了最大内存限制就会出错

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

关于“C# System.TypeInitializationException异常如何处理”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注编程之家行业资讯频道,小编每天都会为大家更新不同的知识点。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


项目中经常遇到CSV文件的读写需求,其中的难点主要是CSV文件的解析。本文会介绍CsvHelper、TextFieldParser、正则表达式三种解析CSV文件的方法,顺带也会介绍一下CSV文件的写方法。 CSV文件标准 在介绍CSV文件的读写方法前,我们需要了解一下CSV文件的格式。 文件示例 一
简介 本文的初衷是希望帮助那些有其它平台视觉算法开发经验的人能快速转入Halcon平台下,通过文中的示例开发者能快速了解一个Halcon项目开发的基本步骤,让开发者能把精力完全集中到算法的开发上面。 首先,你需要安装Halcon,HALCON 18.11.0.1的安装包会放在文章末尾。安装包分开发和
这篇文章主要简单记录一下C#项目的dll文件管理方法,以便后期使用。 设置dll路径 参考C#开发奇技淫巧三:把dll放在不同的目录让你的程序更整洁中间的 方法一:配置App.config文件的privatePath : &lt;runtime&gt; &lt;assemblyBinding xml
在C#中的使用JSON序列化及反序列化时,推荐使用Json.NET——NET的流行高性能JSON框架,当然也可以使用.NET自带的 System.Text.Json(.NET5)、DataContractJsonSerializer、JavaScriptSerializer(不推荐)。
事件总线是对发布-订阅模式的一种实现,是一种集中式事件处理机制,允许不同的组件之间进行彼此通信而又不需要相互依赖,达到一种解耦的目的。&#xA;EventBus维护一个事件的字典,发布者、订阅者在事件总线中获取事件实例并执行发布、订阅操作,事件实例负责维护、执行事件处理程序。
通用翻译API的HTTPS 地址为https://fanyi-api.baidu.com/api/trans/vip/translate,使用方法参考通用翻译API接入文档 。&#xA;请求方式可使用 GET 或 POST 方式(Content-Type 请指定为:application/x-www-for
词云”由美国西北大学新闻学副教授、新媒体专业主任里奇·戈登(Rich Gordon)于2006年最先使用,是通过形成“关键词云层”或“关键词渲染”,对文本中出现频率较高的“关键词”的视觉上的突出。词云图过滤掉大量的文本信息,使浏览者只要一眼扫过文本就可以领略文本的主旨。&#xA;网上大部分文章介绍的是使用P
微软在.NET中对串口通讯进行了封装,我们可以在.net2.0及以上版本开发时直接使用SerialPort类对串口进行读写操作。&#xA;为操作方便,本文对SerialPort类做了一些封装,暂时取名为**SerialPortClient**。
简介 管道为进程间通信提供了平台, 管道分为两种类型:匿名管道、命名管道,具体内容参考.NET 中的管道操作。简单来说,匿名管道只能用于本机的父子进程或线程之间,命名管道可用于远程主机或本地的任意两个进程,本文主要介绍命名管道的用法。 匿名管道在本地计算机上提供进程间通信。 与命名管道相比,虽然匿名
目录自定义日志类NLog版本的日志类Serilog版本的日志类 上个月换工作,新项目又要重新搭建基础框架,把日志实现部分单独记录下来方便以后参考。 自定义日志类 代码大部分使用ChatGPT生成,人工进行了测试和优化,主要特点: 线程安全,日志异步写入文件不影响业务逻辑 支持过期文件自动清理,也可自
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机自动启动的两种常用方法](https://blog.csdn.net/weixin_42288432/article/details/120059296),将里面中的第一种方法做了封装成**AutoStart**类,使
简介 FTP是FileTransferProtocol(文件传输协议)的英文简称,而中文简称为“文传协议”。用于Internet上的控制文件的双向传输。同时,它也是一个应用程序(Application)。基于不同的操作系统有不同的FTP应用程序,而所有这些应用程序都遵守同一种协议以传输文件。 FTP
使用特性,可以有效地将元数据或声明性信息与代码(程序集、类型、方法、属性等)相关联。 将特性与程序实体相关联后,可以在运行时使用反射这项技术查询特性。&#xA;在 C# 中,通过用方括号 ([]) 将特性名称括起来,并置于应用该特性的实体的声明上方以指定特性。
# 简介 主流的识别库主要有ZXing.NET和ZBar,OpenCV 4.0后加入了QR码检测和解码功能。本文使用的是ZBar,同等条件下ZBar识别率更高,图片和部分代码参考[在C#中使用ZBar识别条形码](https://www.cnblogs.com/w2206/p/7755656.htm
C#中Description特性主要用于枚举和属性,方法比较简单,记录一下以便后期使用。 扩展类DescriptionExtension代码如下: using System; using System.ComponentModel; using System.Reflection; /// &lt;
本文实现一个简单的配置类,原理比较简单,适用于一些小型项目。主要实现以下功能:保存配置到json文件、从文件或实例加载配置类的属性值、数据绑定到界面控件。&#xA;一般情况下,项目都会提供配置的设置界面,很少手动更改配置文件,所以选择以json文件保存配置数据。
前几天用SerialPort类写一个串口的测试程序,关闭串口的时候会让界面卡死。网上大多数方法都是定义2个bool类型的标记Listening和Closing,关闭串口和接受数据前先判断一下。我的方法是DataReceived事件处理程序用this.BeginInvoke()更新界面,不等待UI线程
约束告知编译器类型参数必须具备的功能。 在没有任何约束的情况下,类型参数可以是任何类型。 编译器只能假定 System.Object 的成员,它是任何 .NET 类型的最终基类。 如果客户端代码使用不满足约束的类型,编译器将发出错误。 通过使用 where 上下文关键字指定约束。&#xA;最常用的泛型约束为
protobuf-net是用于.NET代码的基于契约的序列化程序,它以Google设计的“protocol buffers”序列化格式写入数据,适用于大多数编写标准类型并可以使用属性的.NET语言。&#xA;protobuf-net可通过NuGet安装程序包,也可直接访问github下载源码:https:/
工作中经常遇到需要实现TCP客户端或服务端的时候,如果每次都自己写会很麻烦且无聊,使用SuperSocket库又太大了。这时候就可以使用SimpleTCP了,当然仅限于C#语言。&#xA;SimpleTCP是一个简单且非常有用的 .NET 库,用于处理启动和使用 TCP 套接字(客户端和服务器)的重复性任务