创建自己的异常并在C#中使用它

New*_*337 0 c# exception custom-exceptions

我试图了解如何以正确的方式使用自定义异常.

我已经多次使用过try/catch但是从来没有说过何时使用自己的类关闭异常.我已经阅读并观看了许多教程,但我无法理解这一点.

这是我的CustomException班级:

[Serializable]
    class CustomException : FormatException
    {
        /// <summary>
        /// Just create the exception
        /// </summary>
        public CustomException()
        : base() {
        }
        /// <summary>
        /// Create the exception with description
        /// </summary>
        /// <param name="message">Exception description</param>
        public CustomException(String message)
        : base(message) {
        }
        /// <summary>
        /// Create the exception with description and inner cause
        /// </summary>
        /// <param name="message">Exception description</param>
        /// <param name="innerException">Exception inner cause</param>
        public CustomException(String message, Exception innerException)
        {
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是我尝试使用它的地方:

    /// <summary>
    /// Checks if parse works
    /// </summary>
    /// <returns></returns>
    public static int ParseInput(string inInt)
    {
        try
        {
            int input = int.Parse(inInt);
            return input;
        }
        catch (CustomException)
        {
            throw new CustomException();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Use only numbers! " + ex.Message);
            return -1;
        }

    }
Run Code Online (Sandbox Code Playgroud)

现在我做错了什么?请问这个程序崩溃了int input = int.Parse(inInt);,它永远不会出现在我的自定义异常中?如果我使用经典Exception类,那一切都有效.

小智 8

您定义的CustomException是一个比基于FormatException的更具体的类(这是继承的内容).您无法使用更具体的异常捕获更通用的异常.只有其他方式.