try
{
//실행하고자 하는 코드
}
catch (예외객체)
{
//예외가 발생했을 때의 처리
}
Exception 클래스는 모든 예외 클래스의 기반 클래스이다. 즉, 특정한 예외만 잡아내고 싶은 것이 아니라면 Eception클래스를 이용해 잔부 잡아낼 수 있다.
하지만 프로그래머가 잡아내고싶은 오류 외의 것도 잡아내서 버그를 만들어낼 수 있기 때문에 사용시에 주의가 필요하다.
throw를 이용하면 예외를 던질 수 있다. 예외를 받을 catch가 함수 내에 없을 경우 함수를 호출한 곳으로 예외를 던진다.
static void DoSomething(int arg)
{
if (arg<10)
Console.WriteLine("arg : {0},arg);
else
throw new Exception("arg가 10보다 큽니다.");
}
static void Main()
{
try
{
DoSomething(13);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
finally절은 try가 실행된 경우 반드시 실행된다. 이곳에 메모리 해제 등 반드시 실행되어야하는 코드를 적는다.
static int Divide(int dividend,int divisor)
{
try
{
Console.WirteLine("Divide() 시작");
return divided/divisor;
}
catch (DivideByZeroException e)
{
Console.WriteLine("Divide() 예외 발생");
throw e;
}
finally
{
Console.WriteLine("Divide() 끝");
}
}
Exception 클래스를 상속하면 사용자 정의 예외클래스를 만들 수 있다.
catch()절 뒤에 when 키워드를 이용해서 제약조건을 걸 수 있다.
class FilterableException : Exception
{
public int ErrorNo {get;set;}
}
try
{
int num = GetNumber();
if (num<0 || num<10)
throw new FilterableException() { ErrorNo = num };
else
Console.WriteLine($"Output : {num}");
}
catch (FilterableException e) when (e.Error <0) // e.Error가 0보다 작을때만 catch
{
Console.WriteLine("Negative input is not allowed");
}
예외객체의 StackTrace 프로퍼티를 이용하면 어디서 예외발생했는지 알려주기 때문에 디버깅에 용이하다.
catch (DivideByZeroException e)
Console.WriteLine(e.stacTrace);