我做了一些用户定义的异常,我想为每个异常添加一个错误级别。例如 userInputerror 和 internalError。我编写这个代码的原因是因为我想了解异常,所以这就是我重新发明轮子而不是使用 log4net 的原因。
我的代码看起来像这样。
我有一个名为 MyException 的类:
namespace ExceptionHandling
{
public class MyException : ApplicationException
{
public MyException(string message)
: base(message)
{
}
public MyException(string message, Exception innerException)
: base(message, innerException)
{
}
}
}
我的一个例外是 IntParseException,这个类看起来像这样:
namespace ExceptionTester
{
class IntParseException : MyException
{
string dataToParse;
public IntParseException(string dataToParse)
: base(" [ERROR] Could not parse " + dataToParse + " to int")
{
this.dataToParse = dataToParse;
}
public IntParseException(string dataToParse, Exception innerexception)
: base(" [ERROR] Could not parse " + dataToParse + " to int", innerexception)
{
this.dataToParse = dataToParse;
}
}
}
在我的主窗体中,我正在处理我的异常,如下所示:
private void btnSave_Click(object sender, EventArgs e)
{
try
{
try
{
int.Parse(txtNumber.Text);
}
catch (Exception ex)
{
throw new IntParseException(txtNumber.Text, ex);
}
}
catch (Exception ex)
{
LogWriter lw = new LogWriter(ex.Source, ex.TargetSite.ToString(), ex.Message);
logwindow.upDateLogWindow();
MessageBox.Show("Please enter a number");
}
}
我正在记录我的异常,该类看起来像这样:
namespace ExceptionTester
{
class LogWriter
{
public LogWriter(string exSource, string exTargetSite, string exMessage)
{
StreamWriter SW;
SW = File.AppendText(@"logfile.txt");
string timeStamp = "[" + DateTime.Now + "] ";
string source = "An error occured in the application ";
string targetSite = ", while executing the method: ";
SW.WriteLine(timeStamp + source + exSource + targetSite +exTargetSite + exMessage);
SW.Flush();
SW.Close();
}
}
}
所以我的问题是,如何将枚举类型添加到我的异常中,这样我就可以选择要记录的异常类型。例如,有时我想记录所有异常,但有时我只想记录 userInputErrors。