2019-2-21.NET中异常类(Exception)

.NET中异常类(Exception)

  异常:程序在运行期间发生的错误。异常对象就是封装这些错误的对象。

  try{}catch{}是非常重要的,捕获try程序块中所有发生的异常,如果没有捕获异常的话,程序运行的线程将会挂掉,更严重的是这些错误有可能会直接抛给用户,让用户看到。所以说在程序的最外层必须要有捕获异常的程序。这样至少确保程序的正常运行。还有一点就是,捕获异常之后需要记录下来,这样对于我们排查问题也是有帮助的。

  什么情况下,不需要捕获异常呢?

  1.发生此类错误的时候,就没必要执行之后的代码的时候,就可以抛出异常了。

  2.在开发封装类,并且发生的错误需要让调用者知道的时候,就可以抛出异常了。

Exception类:

  翻译自:https://msdn.microsoft.com/en-us/library/804f22sf(v=vs.110).aspx

构造函数:4个重载,Exception()、Exception(SerializationInfo, StreamingContext)、Exception(String)、Exception(String, Exception)。

Exception():创建一个异常的实例,异常实例中所有的字段都需要手动再加,初次创建都是默认值。

Exception(SerializationInfo, StreamingContext):暂时不懂。

Exception(String message):创建一个带有错误信息的异常实例。message表示异常信息。

Exception(String message, Exception ex):创建一个异常实例,并为该异常赋值错误信息,如果有内部异常,也一起传进去。如果没有内部异常就传输null。

属性

属性名 类型 解释
Data IDictionary 获取除了异常信息以外,自定义异常的键值对的集合
HelpLink String 获取或设置一个跟异常相关联的帮助文档的地址
HResult int 获取或设置一个特定异常的代码
InnerException Exception 获取当前异常内部的异常实例
Message String 获取异常的错误信息
Source String 获取或设置当前异常发生在那个应用程序中
StackTrace String Gets a string representation of the immediate frames on the call stack.
TargetSite MethodBase 获取当前异常发生的方法

异常类实例方法

Equals(Object object):确定object是否与当前的对象相等。

ToString():把Exception对象转换成字符串,按照指定的格式显示。对Object.ToString () 方法进行重写。

Finalize():允许用户在垃圾回收机制回收之前,释放资源或者清除操作行为。

GetBaseException():在被继承类重写时,返回一个异常或随后的多个异常。

GetHashCode():作为默认的散列函数。

GetType():返回当前实例运行时的类型。

MemberwiseClone():浅复制当前的对象。

 常用的异常类型

 

异常类型 描述
ArgumentException 方法中传进一个非空参数是无效的
ArgumentNullException 方法中传进一个空参数
ArgumentOutOfRangeException 传入的参数超出了有效值的范围
DirectoryNotFoundException 找不到相关目录
DivideByZeroException 分子或分母为0
DriverNotFoundException 驱动无效或者找不到相关驱动
FileNotFoundException 找不到相关文件(文件不存在)
FormatException 格式转换出错,一个类型转换到另外一个类型的时候,格式不一致
IndexOutOfRangeException 索引超出集合的范围
InvalidOperationException 当前操作对象的状态是无效的
KeyNotFoundException 集合中并没有找到对应的键
NotImplementedException 方法或操作没有被实现
NotSupportedException 不支持该方法或操作
ObjectDisposedException 在一个操作上执行一个对象时,发现该对象已经被处理了
OverFlowException 在算法、内存操作,类型转换的时候发生内存溢出
PathTooLongException 一个目录或者文件超出了系统定义的最大长度
PlatformNotSupportedException 当前运行环境不支持该操作
RankException 方法中传进了错误的数组维数
TimeoutException 操作超时
UIFormatException 一个无效的统一资源标识符

 注意:如果自己能判断的异常或者错误,就不要交由.net的异常处理机制。比如字符串转换成数字,应该在转换之前判断是否符合格式要求,而不是直接转换。

例子

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace TestBLL
{
    public class ExceptionTest
    {
        public static void Option(string argument1, int argument2)
        {
            try
            {
                if (argument1 == null)
                {
                    throw new ArgumentNullException("参数为空值");
                }
                string result = argument1;
                if (argument2 == 101)//如果argument2值为101时,抛出参数无效的异常
                {
                    throw new ArgumentException("参数无效");
                }
                if (argument2 > 100)
                {
                    throw new ArgumentOutOfRangeException("参数超出了指定的范围");
                }
                if (!Directory.Exists("D:\Test"))
                {
                    throw new DirectoryNotFoundException("该目录不存在");
                }
                if (argument2 == 0)
                {
                    throw new DivideByZeroException("分母不能为0");
                }
                int num = 10 / argument2;

                string path = @"C:WINDOWSsystem32driversUsbCamIF.sys"; //驱动的默认安装地址
                if (!File.Exists(path))
                {
                    throw new DriveNotFoundException("未找到相关驱动程序");
                }
                if (!File.Exists("D:\Test\test.txt"))
                {
                    throw new FileNotFoundException("该文件路径不存在");
                }
                if (Regex.Match(argument1, "\D").Success)//如果字符中存在非数字字符,在String类型转换成int类型的时候抛出异常
                {
                    throw new FormatException("无法转换类型");
                }
                num = int.Parse(argument1);
                List<string> list = new List<string>() { "123", "456" };
                if (num > list.Count - 1)
                {
                    throw new IndexOutOfRangeException("索引超出了集合的范围");
                }
                string indexStr = list[num];
                Dictionary<int, string> dic = new Dictionary<int, string>() { { 1, "123" }, { 2, "456" } };
                if (!dic.Keys.Contains(num))
                {
                    throw new KeyNotFoundException("并为找到相应的键");
                }
                result = dic[num];
            }
            catch (Exception e)
            {
                e.HelpLink = "https://msdn.microsoft.com/en-us/library/system.exception(v=vs.110).aspx";
                e.Source = "Test";
                throw new Exception("方法中出现异常",e);//在此处捕获所有的异常,并统一抛出去
            }
        }
    }
}

异常类实例

  

原文地址:https://www.cnblogs.com/liuqifeng/p/10412705.html