当前位置: 移动技术网 > IT编程>开发语言>.net > C# 自定义异常总结及严格遵循几个原则

C# 自定义异常总结及严格遵循几个原则

2017年12月12日  | 移动技术网IT编程  | 我要评论

oh必胜奉顺英国语,为君入梦,串珠教程

在c#中所有的异常类型都继承自system.exception,也就是说,system.exception是所有异常类的基类. 总起来说,其派生类分为两种:
1. systemexception类: 所有的clr提供的异常类型都是由systemexception派生。
2. applicationexception类: 由用户程序引发,用于派生自定义的异常类型,一般不直接进行实例化。

创建自定义异常类应严格遵循几个原则
1. 声明可序列化(用于进行系列化,当然如果你不需要序列化。那么可以不声明为可序列化的)
2. 添加一个默认的构造函数
3. 添加包含message的构造函数
4. 添加一个包含message,及内部异常类型参数的构造函数
5. 添加一个序列化信息相关参数的构造函数.
复制代码 代码如下:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.io;
using system.runtime.serialization.formatters.binary;
namespace consoleapplication3
{
[serializable] //声明为可序列化的 因为要写入文件中
public class payoverflowexception : applicationexception//由用户程序引发,用于派生自定义的异常类型
{
/// <summary>
/// 默认构造函数
/// </summary>
public payoverflowexception() { }
public payoverflowexception(string message)
: base(message) { }
public payoverflowexception(string message, exception inner)
: base(message, inner) { }
//public payoverflowexception(system.runtime.serialization.serializationinfo info,
// system.runtime.serialization.streamingcontext context)
// : base(info, context) { }
}
internal class employee
{
public int id { get; set; }
public string name { get; set; }
/// <summary>
/// current pay
/// </summary>
public int currpay { get; set; }
public employee() { }
public employee(int id, string name, int currpay)
{
this.id = id;
this.name = name;
this.currpay = currpay;
}
/// <summary>
/// 定义一个givebunus的虚方法以供不同的派生类进行重载
/// </summary>
/// <param name="amount">奖金额度</param>
public virtual void givebunus(int amount)
{
//用一个临时变量记录递增之前的值
var pay = currpay;
this.currpay += amount;
if (currpay > 10000)
{
//发生异常,将currpay的值进行恢复,
//并抛出异常,外部程序捕获次异常
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)
{
console.writeline("**** 创建employee对象,并用try/catch捕获异常 *****");
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();
//以字节方式写入
//byte[] buffer = system.text.encoding.default.getbytes(ex.message);
//int leng = 0;
//leng = buffer.getlength(0);
//file.write(buffer, 0, leng);
//file.close();
}
catch (exception ex1)
{
var inner = new payoverflowexception(ex.message, ex1);
throw inner;
}
}
}
}
}

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网