C# 自定义异常的方法源码演示及说明

时间:2021-05-01 23:41:48

内容之余,把做工程过程中较好的内容段备份一下,下边内容是关于C# 自定义异常的方法演示及说明的内容,希望能对各位朋友有一些好处。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace ConsoleApplication3
{
{
public PayOverflowException() { }
public PayOverflowException(string message)
: base(message) { }
public PayOverflowException(string message, Exception inner)
: base(message, inner) { }
}
internal class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public int CurrPay { get; set; }
public Employee() { }
public Employee(int id, string name, int currpay)
{
this.ID = id;
this.Name = name;
this.CurrPay = currpay;
}
public virtual void GiveBunus(int amount)
{
var pay = CurrPay;
this.CurrPay += amount;
if (CurrPay > 10000)
{
this.CurrPay = pay;
var ex = new PayOverflowException("The employee's max pay should be no more than 10000.");
throw ex;
}
}
}
class Program
{
static void Main(string[] args)
{
var emp = new Employee(10001, "Yilly", 8000);
try
{
emp.GiveBunus(3000);
}
catch (PayOverflowException ex)
{
Console.WriteLine("异常信息:{0}n发生于{1}类的{2}方法", ex.Message,
ex.TargetSite.DeclaringType, ex.TargetSite.Name);
try
{
var file = new FileStream(@"c:customerexception.txt", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(file, ex);
file.Close();
}
catch (Exception ex1)
{
var inner = new PayOverflowException(ex.Message, ex1);
throw inner;
}
}
}
}
}

值得注意的是:在实例化的时候调用的是PayOverflowException(stringmessage,Exceptioninner)构造函数,如果本程序如果有其他程序在调用的时候,可以通过.InnerExcetpion的Message属性进行查看内部异常。