본문 바로가기
C#/Effective C#

[Effective C#] Item 50 예외 필터의 다른 활용 예를 살펴보라

by 코모's 2023. 6. 12.
반응형

예외필터를 통해 다양한 방법으로 여러가지 기능을 제공할 수 있다.

 

첫번째로 항상 false만을 반환하여 제한된 타입에 대해서만 로그를 출력할 수 있다.

 

try
{
    data = MakeWebRequest();
}
catch (Exception e) when (ConsoleLogException(e))
{
}
catch (TimeoutException e) when (failures++ < 10)
{
    WriteLine("Timeout error: trying again");
}

public static bool ConsoleLogException(Exception e)
{
    var oldColor = Console.ForegroundColor;
    Console.ForegroundColor = ConsoleColor.Red;
    WriteLine("Error: {0}", e);
    Console.ForegroundColor = oldColor;
    
    return false;
}

 

또 다른 예로 디버깅을 수행할 때는 catch문 내의 예외 처리 루틴을 수행하지 않도록 할 수 있다.

try
{
    data = MakeWebRequest();
}
catch (Exception e) when (ConsoleLogException(e))
{
}
catch (TimeoutException e) when ((failures++ < 10) &&
    (!System.Diagnostics.Debugger.IsAttached))
{
    WriteLine("Timeout error: trying again");
}

예외 처리 필터의 동작 방식에 대해 잘 이해한다면 여러 가지 방식으로 운용이 가능하다.

반응형