[C# 6.0] 예외 필터(Exception filter)

eunjin lee·2023년 1월 9일
0

C# 9.0 프로그래밍

목록 보기
45/50

비주얼베이직과 F# 언어에서 지원하던 예외 필터를 이제야 C#에서도 사용할 수 있게 되었다.

try { }
catch (예외타입 e) when (조건식) { }

✍ 샘플 코드

  string filePath = @"c:\teamp\test.txt";
  try
  {
      string txt = File.ReadAllText(filePath);
  }
  catch (FileNotFoundException e) when (filePath.IndexOf("temp") != -1)
  {
      Console.WriteLine(e.ToString());
  }
  • 조건식이 실행되는 시점은 처리 핸들러가 실행되는 시점이 아니기 때문에 아래와 같이 부가적인 작업을 할 수 있다.
    static void Main(string[] args)
    {
        string filePath = @"c:\temp\test.txt";
        try
        {
            string txt = File.ReadAllText(filePath);
        } 
        catch (FileNotFoundException e) when (Log(e))
        {
            Console.WriteLine(e.ToString());
        }
    }

    static bool Log(Exception e)
    {
        Console.WriteLine("Log : "+e.ToString());
        return false;
    }
  • 위의 코드가 아래의 코드와 동일하다고 생각할 수 있다.
    static void Main(string[] args)
    {
        string filePath = @"c:\temp\test.txt";
        try
        {
            string txt = File.ReadAllText(filePath);
        } 
        catch (FileNotFoundException e)
        {
            Console.WriteLine("Log : "+e.ToString());
            throw;
        }
    }
  • 그러나 두 코드가 완전히 같지는 않다. 예외필터는 닷넷의 IL(Intermediate Language) 수준에서 지원하기 때문에 기존의 C# 코드로 변경해서 처리하지 않고 예외 필터의 IL 코드로 직접 변경된다.

  • 예외 필터를 사용하면 아래와 같이 동일한 예외타입의 catch 구문을 여러 개 두는 것도 가능하다. when 조건문은 여러 번 실행되지만 선택되는 catch 예외 핸들러는 하나이다.

✍ 샘플 코드

    static void Main(string[] args)
    {
        string filePath = @"c:\temp\test.txt";
        try
        {
            string txt = File.ReadAllText(filePath);
        } 
        catch (FileNotFoundException e) when (Log(e))
        {
            Console.WriteLine("1");
        }
        catch (FileNotFoundException e) when (Log(e)) //동일한 예외 필터도 가능
        {
            Console.WriteLine("2");
        }
        catch (FileNotFoundException e) //필터 없이도 가능
        {
            Console.WriteLine("3");
        }

    }

        static bool Log(Exception e)
        {
            return false;
        }

✅ 결과

3

🧐 try/catch/finally 절에서도 비동기호출을 처리할 수 있다.

0개의 댓글