2013-08-29 1 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; 
} 

내가 시도 캐치 블록이 문을 넣을 수 있습니다 : 여기

내 코드? 이벤트 처리기에서 처리 한 많은 오류 메시지가 있기 때문에. 따라서 많은 이벤트 핸들러를 작성하는 대신 한 번만 작성하여 처리 할 수 ​​있습니까?

+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 블록을 사용하여 예외를 캡처 할 수 있습니다. 원래 Exception 유형은 Exception에 캐스트 한 경우에도 보존됩니다.

try 
{ 
    //do something 
} 
catch (Exception ex) 
{ 
    //capture exception and provide to target method as a parameter 
    MethodName(ex); 
} 

특정 유형의 예외를 잡아 여러 가지 방법으로 처리 할 수도 있습니다. 당신이 try { ... } catch { ... } 블록이 아닌 다른 뭔가를 사용하여 예외를 처리하려고처럼

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() 메소드에서 customer 객체가 null인지 아닌지를 확인하고 소득이 null인지 아닌지를 확인해야하는 processincome() 메서드를 고려해야한다고 가정합니다. 두 방법 모두 다른 오류 메시지를 표시합니다. 모든 예외를 처리하는 일반적인 catch 블록을 사용할 수 있습니까? – user2619542

0

는 것 같습니다. 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을 기반으로하는 메소드를 선언 할 수 있습니다.

관련 문제