ユーザー定義の例外をいくつか作成しましたが、例外ごとにエラーレベルを追加したいと考えています。 userInputerror、internalErrorなどがあります。私がこれをコーディングしているのは、例外について学びたいからです。だから、私はlog4netを使うのではなく、ホイールを再開発しているのです。列挙型「エラーレベル」のユーザー定義例外
私のコードは次のようになっています。
私はMyExceptionというクラスがあります。私の例外の一つはIntParseExceptionある
namespace ExceptionHandling
{
public class MyException : ApplicationException
{
public MyException(string message)
: base(message)
{
}
public MyException(string message, Exception innerException)
: base(message, innerException)
{
}
}
}
、このクラスは次のようになります。私のメインフォームで
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();
}
}
}
だから私の質問は、私は私の例外に列挙型を追加するにはどうすればよいことが可能に私が選択することのためになるだろうされている例外の種類私はログに記録したい。たとえば、somepointではすべての例外をログに記録したいが、別の時にはuserInputErrorsだけを記録したい。
プログラムを実行している間に変更することはできません。私はコード内の何かを変更する必要はありません。ちょうどその列挙型は、そのようなものに使用することができると思ったが、私はそれを行う方法がわからない。 –
一般的なガイドラインとして、あなたが提案していることは、設計上の決定が悪いと言うでしょう。つまり、例外処理は非常に本質的に「リアルタイム」なものです。私は、この例外処理パラダイムに何の利益も見られません。 – Didaxis
また、タイプに基づいて処理する例外を「変更する」こともできます。列挙型は単に不必要な "荒廃"です。 – Didaxis