C# 예외처리

선비Sunbei·2023년 1월 10일
0

C#

목록 보기
12/18
post-thumbnail

try-catch

try-catch는 오류가 발생할 경우 프로그램을 멈추지 않고, catch문으로 넘어가서 오류 이유와 함께 후처리 후 다음 메서드로 넘어간다.

using System;

namespace Study26
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 4;
            int b = 0;
            try
            {
                a /= b;
            }catch(Exception e)
            {
                Console.WriteLine(e.Message);
                // Attempted to divide by zero.
            }
            finally
            {
                Console.WriteLine("try-catch문 종료");
                // try-catch문 종료
            }
        }
    }
}

finally는 오류가 발생하든 발생하지 않든간에 맨 마지막에 실행시킨다.

사용자 정의 예외처리

using System;

namespace Study26
{
    class Program
    {
        class CustomException : Exception
        {
            public override string Message
            {
                get
                {
                    return "자연수가 아닙니다.";
                }
            }
        }

        static void Main(string[] args)
        {
            int a = -2;
            try
            {
                if (a <= 0)
                    throw new CustomException();
            }catch(CustomException e)
            {
                Console.WriteLine(e.Message);
            }

            // 자연수가 아닙니다.
        }
    }
}

다음과 같이 Exception을 상속받은 후 예외처리를 하고 싶을 때 throw new Exception()으로 넘기면 catch문으로 넘어간다.
throw new Exception()은 꼭 try-catch문 안이 아니라 외부에 적어도 된다. 이 경우 조건문과 함께 디버깅용으로 사용한다.

try-catch : when

using System;

namespace study27
{
    class Program
    {
        class CustomException : Exception
        {
            private string str;
            public override string Message { 
                get {
                    return str;
                } 
            }
            public CustomException(string str)
            {
                this.str = str;
            }
        }
        static void Main(string[] args)
        {
            int a = 20;
            try
            {
                if (a <= 0)
                    throw new CustomException("error001");
                if (a >= 100)
                    throw new CustomException("error002");
                if (a >= 10 && a <= 90)
                    throw new CustomException("error003");

                Console.WriteLine("예외처리되지 않았습니다.");
            }catch(CustomException e) when (e.Message.Contains("error001")){
                Console.WriteLine("자연수만 허용됩니다.");
            }
            catch (CustomException e) when (e.Message.Contains("error002"))
            {
                Console.WriteLine("100보다 작아야 합니다.");
            }
            catch (CustomException e) when (e.Message.Contains("error003"))
            {
                Console.WriteLine("10보다 크거나 90보다 작으면 안됩니다.");
            }
            finally
            {
                Console.WriteLine("정답은 1~9, 91~99의 숫자입니다.");
            }
        }
		/*
        10보다 크거나 90보다 작으면 안됩니다.
		정답은 1~9, 91~99의 숫자입니다.
        */
    }
}

다음과 같이 catch문 옆에 when을 써서 같은 예외처리라도 조건을 걸 수 있다.
주의할 점은 when 다음에 괄호()를 써서 조건을 걸어야 한다.
if문 옆에 괄호 쓰는 것과 같은 뜻이다.

0개의 댓글