비주얼베이직과 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 절에서도 비동기호출을 처리할 수 있다.