예외 필터 예제코드
C# 6.0 부터 catch 절에서 특정 조건에 만족하는 예외 객체에 대해서 예외 처리를 할 수 있는 예외 필터가 도입됐습니다. 예제 코드로 확인합니다.
class FilterableException : Exception {
public int ErrorNo { get; set; }
}
class Program {
static void Main(string[] args) {
Console.Write("Enter Number Between 0~10 : ");
string input = Console.ReadLine();
try {
int num = Int32.Parse(input);
if (num < 0 || num > 10)
throw new FilterableException()
{
ErrorNo = num
};
else
Console.WriteLine($"Output : {num}");
}
catch(FilterableException e) when (e.ErrorNo < 0) {
Console.WriteLine("입력된 수가 0보다 작으면 안됩니다");
}
catch(FilterableException e) when (e.ErrorNo > 10) {
Console.WriteLine("입력된 수가 10보다 크면 안됩니다");
}
finally {
Console.WriteLine("프로그램 종료");
}
}
}
결과물