11/06/2009

Custom Exception in C#

예외를 직접 만들어 써보자.


//custom exception
[Serializable]
public class CarIsDeadException : ApplicationException
{
    public CarIsDeadException() { }
    public CarIsDeadException(string message)
        : base(message) { }

    //to handle "inner exceptions"
    public CarIsDeadException(string message, System.Exception inner)
        : base(message, inner) { }

    //to handle the serialization of type.
    protected CarIsDeadException(
        System.Runtime.Serialization.SerializationInfo info,
        System.Runtime.Serialization.StreamingContext context)
        : base(info, context) { }
}

//using
public class Main
{
    public Main()
    {
        //using basic
        try
        {
            CarIsDeadException ex = new CarIsDeadException("error");
            throw ex;
        }
        catch(CarIsDeadException e)
        {
            string errorMessage = e.Message;
            System.Windows.Forms.MessageBox.Show(errorMessage);
            //using inner exception
            try
            { ... }
            catch (Exception e2)
            {
                throw new CarIsDeadException(e.Message, e2);
            }
        }
    }
}

댓글 없음:

댓글 쓰기