[C# 문법] 사용자 지정 예외 클래스 만들기

참조

  • Effective C# 개정판 3판

1. 소개

  • 예외는 런타임에 발생하는 오류이며 제대로 처리하지 않으면 프로그램 실행의 정상적인 흐름을 종료합니다.
  • 예외가 발생하면 실제 스택 추적 또는 예외 메시지를 사용자에게 표시하지 않을 수 있습니다.
  • 사용자 정의 예외는 프로그램 실행 중 오류가 발생할 때 예외에 명확하고 의미 있고 사용자에게 친숙한 정보를 추가하는 데 사용할 수 있습니다.

2. 예외 클래스 목적

  • catch문을 작성할 때 예외의 런타임 타입에 따라 서로 다른 작업을 수행하는게 일반적입니다.
try
{
    Print();
}
catch (MyFirstApplicationException e1)
{
    FixProblem(e1);
}
catch (AnotherApplicationException e2)
{
    ReportErrorAndContinue(e2);
}
catch (YetAnotherApplicationException e3)
{
    ReportErrorAndShutdown(e3);
}
catch (Exception e)
{
    ReportGenericError(e);
    throw;
}
finally
{
    CleanupResources();
}
  • 따라서 특정 예외 상황에 특별한 처리를 하고 싶을 때 예외 클래스를 만드는 것이 좋습니다.
  • 다른 작업이나 복구 메커니즘으로 이어질 가능성이 있다면, 그 내용을 예외 클래스에 담는 것이 도움이 됩니다.

4. 예외 클래스 만들기

  • 예외 클래스 만드는 방법에 대해서 알려드리겠습니다.

  • 새로운 예외 클래스를 작성할 떄는 반드시 4개의 생성자를 작성해야 합니다.
// 기본 생성자
public Exception();
// 에러 메시지를 포함하는 생성자
public Exception(string);
// 에러 메시지와 내부 예외를 포함하는 생성자
public Exception(string, Exception);
// 입력 스트림을 이용하는 생성자
protected Exception(SerializationInfo, StreamingContext);
  • 마지막 생성자는 예외 클래스가 serialize 가능해야 함을 의미하는 것이기도 합니다.
[Serializable]
public class LoginException : Exception
{
    public LoginException() : base()
    {
    }

    public LoginException(string s) : base(s)
    {
    }

    public LoginException(string s, Exception e) : base(s, e)
    {
    }

    protected LoginException(SerializationInfo info,
        StreamingContext cxt) : base(info, cxt)
    {
    }
}

using System;
using System.Runtime.Serialization;

namespace Chapter47
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string id = string.Empty;
                string pw = "1234";
                // 로그인
                Login(id, pw);
            }
            catch(LoginException myException)
            {
                Console.WriteLine(myException.Message);
                Console.WriteLine("ID:{0}, Password:{1}", myException.ID, myException.Password);
            }
        }

        static void Login(string id, string pw)
        {
            if(string.IsNullOrEmpty(id) == true || string.IsNullOrEmpty(pw))
            {
                throw new LoginException()
                {
                    ID = id,
                    Password = pw
                };
            }
        }
    }

    [Serializable]
    public class LoginException : Exception
    {
        // 기본 생성자
        public LoginException() : base() { }
        // 에러 메시지를 포함하는 생성자
        public LoginException(string message) : base(message) { }
        // 에러 메시지와 내부 예외를 포함하는 생성자
        public LoginException(string message, Exception e) : base(message, e) { }
        // 입력 스트림을 이용하는 생성자
        public LoginException(SerializationInfo info, StreamingContext cxt) : base(info, cxt) { }
        public string ID
        { 
            get; set; 
        }
        public string Password
        {
            get;set;
        }
    }
}
'Chapter47.LoginException' 형식의 예외가 Throw되었습니다.
ID:, Password:1234

5. 정리

  • 응용 프로그램의 예외 처리에 더 많은 기능을 추가하려는 경우 또는 사용자에게 추가 정보를 제공하는 것이 의미가 있는 경우에는 사용자 지정 예외 클래스를 구현하는 것이 좋습니다.
  • 또한, 예외를 별도로 다루는 것이 적절하다고 생각되는 오류라면 사용자 지정 예외 클래스를 구현해서 사용하는것이 좋습니다.
728x90

이 글을 공유하기

댓글

Designed by JB FACTORY