我们可以将异常附加到事件处理程序吗?
这是我的代码:
if (customer == null)
{
eventListener.HandleEvent(Severity.Informational, line.GetType().Name, String.Format("Could not find the customer corresponding to the taxId '{0}' Current Employment will not be imported.", new TaxId(line.TaxId).Masked));
return;
}
if (incomeType == null)
{
eventListener.HandleEvent(Severity.Warning, line.GetType().Name, String.Format("The income type of '{0}' in the amount of {1:c} is not a known type.", line.Type, line.Amount));
return;
}
我可以将这些语句放在try catch块中吗?因为我有许多由事件处理程序处理的错误消息。因此,我们可以通过只编写一次来实现它,而不是编写很多这个事件处理程序吗?
答案 0 :(得分:1)
根据您的评论,您似乎想要捕获异常并将其传递给要处理的方法。
向您的方法添加Exception
类型的参数。
public void MethodName(Exception error, ... )
{
if (error is NullReferenceException)
{
//null ref specific code
}
else if (error is InvalidOperationException)
{
//invalid operation specific code
}
else
{
//other exception handling code
}
}
您可以使用Try / Catch块捕获异常。即使您将其转换为异常,也会保留原始的异常类型。
try
{
//do something
}
catch (Exception ex)
{
//capture exception and provide to target method as a parameter
MethodName(ex);
}
您还可以捕获特定类型的异常并使用不同的方法处理它们。
try
{
//do something
}
catch (InvalidOperationException ioe)
{
//captures only the InvalidOperationException
InvalidOpHandler(ioe);
}
catch (NullReferenceException nre)
{
//captures only the NullReferenceException
NullRefHandler(nre);
}
catch (Exception otherException)
{
//captures any exceptions that were not handled in the other two catch blocks
AnythingHandler(otherException);
}
答案 1 :(得分:0)
看起来您尝试使用try { ... } catch { ... }
块之外的其他内容来处理异常。我不会使用其他任何东西来处理C#中的异常 - try
,catch
和finally
是专门为此任务构建的。
看起来你正在写一些东西来处理输入验证。关于异常是否适合它的论证,但如果你是,你应该重构这样的事情:
if (customer == null)
{
throw new ArgumentNullException("customer",
String.Format("Could not find the customer corresponding to the taxId '{0}' Current employment will not be imported.",
new TaxId(line.TaxId).Masked)
);
然后在调用代码中:
try
{
// code that can throw an exception
}
catch (ArgumentNullException ex)
{
someHandlingCode.HandleEvent(ex);
// if you need to rethrow the exception
throw;
}
它的长短 - 是的,你可以声明一个方法,它将异常作为一个参数并根据它做一些事情。