继承Exception 自定义异常信息:
案例如下:
public class MyCustomException : System.Exception
{
//this:引用自身类的当前实例构造
public MyCustomException(string message, int errorCode)
: this(message, errorCode, 0, null) { }
//base:用指定的内容去初始化父类相对应的构造函数中的变量信息
public MyCustomException(string message, int errorCode, int level, DateTime? happenTime)
: base(message)
{
ErrorCode = errorCode;
Level = level;
HappenTime = happenTime;
}
public int ErrorCode { get; set; }
public int Level { get; set; }
public DateTime? HappenTime { get; set; }
}
//调用方式
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}");
}
string input = Console.ReadLine();