모름

예외 던지기

 

C#에는 예외를 처리해주는 try~catch문이 있습니다. 여기에 더해 throw 라는 예외 던지기가 존재합니다. throw를 통해 예외를 '그냥' 아무곳에 던져버리면 catch문이 알아서 이 예외를 받아냅니다. 예제 코드를 통해 이해하는게 제일 빠를듯 합니다.

 

 

 


 

 

 

throw문 예제코드

 

class Program {
    static void DoSomething(int arg) {
        if(arg < 10) {
            Console.WriteLine($"arg : {arg}");
        }
        else {
            throw new Exception($"arg가 10보다 크면 안됩니다. 현재 arg : {arg}");
        }
    }

    static void Main(string[] args) {
        try {
            DoSomething(13);
        }
        catch(Exception e) {
            Console.WriteLine(e.Message);
        }
    }
}

 

 

 

출력

 

 

 

 


 

 

 

throw식 예제코드

 

앞서 따라한 예제코드가 throw'문' 이었다면 좀 더 간편하게 표현할 수 있는 throw'식'이 있습니다. 이에 대해서 예제 코드를 작성해봅니다.

 

class Program {
    static void Main(string[] args) {
        try {
            int? a = null;
            int b = a ?? throw new ArgumentNullException();
        }
        catch(ArgumentNullException e) {
            Console.WriteLine(e);
        }

        try {
            int[] arr = new[] { 1, 2, 3 };
            int index = 4;
            int value = arr[index >= 0 && index < 3 ? index : throw new IndexOutOfRangeException()];
        }
        catch(IndexOutOfRangeException e) {
            Console.WriteLine(e);
        }
    }
}

 

참고1 : (int? a) nullable 타입이며 null 선언이 가능합니다.

참고2 : ??연산자는 null 병합 연산자라고도 불립니다. 왼쪽 피연산자 (즉, 'a')가 null이면 오른쪽 피연산자를 리턴합니다. 여기선 예외를 던졌죠. 그리고 a가 null이 아니면 왼쪽 피연산자 (즉 여기선 자기자신)을 리턴합니다.

 

 

 

 

 

 

출력

 

 

 

 


 

 

 

finally 절 예제코드

 

finally 절은 try~catch문의 마지막에 연결해 사용합니다. finally 절이 소속된 try이 절이 실행된다면 어떤 경우라도 finally 절이 실행됩니다. try이에 return, throw문 등이 사용되어도 말입니다. 예제 코드로 살펴보겠습니다.

 

class Program {
    static int Devide(int dividend, int divisor) {
        try {
            Console.WriteLine("Divide() 시작");
            return dividend / divisor;
        }
        catch(DivideByZeroException e) {
            Console.WriteLine("Divide() 예외 발생");
            throw e;
        }
        finally {
            Console.WriteLine("Divide() 종료");
        }
    }

    static void Main(string[] args) {
        try {
            Console.Write("피제수를 입력하세요 : ");
            String temp = Console.ReadLine();
            int dividend = Convert.ToInt32(temp);

            Console.Write("제수를 입력하세요 : ");
            temp = Console.ReadLine();
            int divisor = Convert.ToInt32(temp);

            Console.WriteLine("{0}/{1} = {2}", dividend, divisor, Devide(dividend, divisor));
        }
        catch(FormatException e) {
            Console.WriteLine("에러! : " + e.Message);
        }
        catch (DivideByZeroException e) {
            Console.WriteLine("에러! : " + e.Message);
        }
        finally {
            Console.WriteLine("프로그램 종료");
        }
    }
}

 

 

 

 

 

 

출력

 

 

첫 번째 출력입니다. 제수(나누는 수)에 잘못된 입력값이 들어가서 예외가 발생했으며 이 예외를 잡아냈습니다.

 

 

두 번째 출력입니다. 피제수를 0으로 나누려고 했기 때문에 계산 시 예외가 발생했고 이를 잡아냈습니다.

 

 

마지막 출력이며 정상적으로 프로그램이 작동한 모습입니다.