방프리

21.10.01 Chapter5. 예외처리 (Item 50) 본문

C#/Effective C#

21.10.01 Chapter5. 예외처리 (Item 50)

방프리 2021. 10. 1. 22:22

Item 50 : 예외 필터의 다른 활용 예를 살펴보라

 

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

첫 번째로 항상 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");
}

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

Comments