2013-08-29 91 views
-2

我们可以将异常附加到事件处理程序吗?我们可以在事件处理程序中添加异常吗?

这里是我的代码:

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; 
} 

可我把尝试catch块这些语句?因为我有很多错误消息是由事件处理程序处理的。所以不是写很多这个事件处理程序,我们可以通过只写一次来完成它?

+0

你问你是否可以捕获异常并将其传递给'HandleEvent'方法? – JeremiahDotNet

+0

'eventListener'的类型是什么? – jdphenix

+0

它可能是有帮助的阅读此:http://msdn.microsoft.com/en-us/library/ms173160.aspx –

回答

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); 
} 
+0

我有很多方法,我必须检查一个空例外。假设在processcustomer()方法中,我需要检查客户对象是否为null,并考虑另一个方法processincome(),其中我必须检查收入是否为null。两种方法都显示不同的错误消息我们可以使用处理所有异常的通用catch块吗? – user2619542

0

它看起来像你试图处理异常使用try { ... } catch { ... }块以外的东西。我不会使用任何其他方式处理C#中的异常 - try,catchfinally是专门为此任务构建的。

它看起来像你正在写东西来处理输入验证。有一个说法是例外是否是适合的,但如果你是,你应该重构为这样的事情:

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; 
} 

长和简而言之 - 是的,你可以声明一个方法,它将一个异常作为参数并根据on进行一些操作。

相关问题