这是使用自定义异常的正确方法吗?

时间:2015-09-12 20:58:59

标签: c# exception

这是我最后一次提出有关此问题的问题:)。

我有几个小时的时间现在试图了解自定义异常处理,如何以及何时使用它。我之前已经两次问过这个问题了,我真的很抱歉这么多次,但是你们这里的人总是很好解释和帮助!

我想我现在知道了......只是想要你的想法。

我知道有更好的方法可以解决这个问题,但主要目的是让我了解自定义异常和抛出语句。

这是我的自定义异常类:

[Serializable]
    class CustomException : Exception
    {
        /// <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 ex)
        : base(message, ex) {
        }
    }

这可能是我使用它的类:

public static int ParseParse(string inInt)
        {
            int input;
            if (!int.TryParse(inInt, out input))
            {
                MessageBox.Show("Only use numbes!");
                return -1;
            }
            else if (input <= 0)
            {
                try
                {
                    throw new CustomException("The price must be greater than zero");
                }
                catch (CustomException ex)
                {
                    MessageBox.Show(ex.Message, "No negativ numbers or zero");
                    return -1;
                }

            }
            else
            {
                return input;
            }

        }

这就是我在上面称这个课程的地方:

if (HelpClass.ParseInput(txtPrice.Text) <= 0)
                {
                    ok = false;
                }
                else
                {
                    newGame.Price = HelpClass.ParseInput(txtPrice.Text);
                    _mGames.AddNewGame(newGame);
                }

1 个答案:

答案 0 :(得分:2)

如果你真的想在这里抛出一个异常,那么用相同的方法捕获它就没有意义 - 只需一起摆脱异常处理。您应该在ParseParse中抛出异常并将其捕获到调用层次结构中的其他位置。请记住,异常会在调用堆栈中向上传播,因此,如果尚未处理异常,您甚至可以在Main方法中捕获异常,无论抛出异常的位置如何。

else if (input <= 0)
{
    throw new CustomException("The price must be greater than zero");
}

现在你可以使用这样的方法:

try
{
    if (HelpClass.ParseInput(txtPrice.Text) <= 0) // No more code in the try block will be executed if ParseParse throws an exception
    {
        ok = false;
    }
    else
    {
        newGame.Price = HelpClass.ParseInput(txtPrice.Text);
        _mGames.AddNewGame(newGame);
    }
}
catch (CustomException ex)
{
    // exception handling logic goes here
}