日期:2014-05-19  浏览次数:20841 次

C#中如何让自己编写 的类中的错误能被try catch 语句捕获?
如题,自己编写一个类,类中有一成员函数DoSomething()
public   void   DoSomthisng()
{
          if(....)
                  //错误处理和描述
          else
                  //处理
       
}
想实现的效果是当用户用try语句
        try
        {
                SomeClass.DoSomethin();
        }
        cahtch   (Exception   err)
        {
                message.Text=err.ToString();  
        }
捕获错误时,能够显示我所定义的错误描述,这个能实现吗?若可以的话该如何实现?
期待大家的赐教

------解决方案--------------------

throw new Exception( "这里发现一个错误 ");
来引发一个异常!
------解决方案--------------------
捕获异常后自己重新throw一个自定义的异常
呵呵
------解决方案--------------------
给个自定义异常的Demo
using System;

namespace Exercise
{
class ExceptionDemo
{
static void Main(string[] args)
{
int num;

try
{
num = Convert.ToInt32(Console.ReadLine());
if (num < 0)
throw new myException(2000, "小于零 ");
}
catch(myException err)
{
Console.WriteLine(err.Number);
Console.WriteLine(err.Message);
}
}
}

class myException:System.ApplicationException
{
private uint errorNumber;

public myException():base( "myException "){}

public myException(uint Number, string Message):base(Message)
{
this.errorNumber = Number;
}

public uint Number
{
get{return this.errorNumber;}
}
}
}

------解决方案--------------------
public void DoSomthisng()
{
if(....)
throw new Exception( "错误处理和描述 ");
else
//处理

}
------解决方案--------------------
throw 一个新的Exception
------解决方案--------------------
public class MyException : Exception
{
// 这里写一些你自己的定义
}

public class MyClass
{
if (代码异常)
{
// 做必要处理
// 实例化自定义异常
MyException ex = new MyException();
// 这里定义你的ex
// 抛出异常
throws ex;
}
else
{
try
{
// 运行正常代码
}
catch (Exception ex)
{
// 必要的处理
// 实例化自定义异常
MyException ex = new MyException();
// 这里定义你的ex
// 抛出异常
throws ex;
}
}