创建自己的异常c#

Eva*_*ons 21 c# exception-handling exception try-catch

以下是我的C#书中的示例,我遇到了一个在Visual Studio中不起作用的书籍示例.它涉及创建自己的异常,尤其是阻止你取负数的平方根.但是,当我使用"throw new"创建NegativeNumberException时,我收到一条错误消息"无法找到类型或命名空间名称'NegativeNumberException'(您是否缺少using指令或程序集引用?)"

如果这不是正确的方法,我如何创建自己的例外?也许我的书已经过时了?这是代码:

class SquareRootTest
{
    static void Main(string[] args)
    {
        bool continueLoop = true;

        do
        {
            try
            {
                Console.Write("Enter a value to calculate the sqrt of: ");
                double inputValue = Convert.ToDouble(Console.ReadLine());
                double result = SquareRoot(inputValue);

                Console.WriteLine("The sqrt of {0} is {1:F6)\n", inputValue, result);
                continueLoop = false;
            }
            catch (FormatException formatException)
            {
                Console.WriteLine("\n" + formatException.Message);
                Console.WriteLine("Enter a double value, doofus.\n");
            }
            catch (NegativeNumberException negativeNumberException)
            {
                Console.WriteLine("\n" + negativeNumberException.Message);
                Console.WriteLine("Enter a non-negative value, doofus.\n");
            }
        } while (continueLoop);
    }//end main
    public static double SquareRoot(double value)
    {
        if (value < 0)
            throw new NegativeNumberException(
                "Square root of negative number not permitted.");
        else
            return Math.Sqrt(value);
    }
}
Run Code Online (Sandbox Code Playgroud)

Dmi*_*nko 51

Exception仅仅是一个像净许多其他类.恕我直言,用户定义的例外有两个棘手的事情:

  1. Exception继承您的异常类,而不是从过时的ApplicationException继承
  2. 用户定义的异常应该有许多构造函数 - 在典型情况下为4

像这样的东西:

public class NegativeNumberException: Exception {
  /// <summary>
  /// Just create the exception
  /// </summary>
  public NegativeNumberException()
    : base() {
  }

  /// <summary>
  /// Create the exception with description
  /// </summary>
  /// <param name="message">Exception description</param>
  public NegativeNumberException(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 NegativeNumberException(String message, Exception innerException)
    : base(message, innerException) {
  }

  /// <summary>
  /// Create the exception from serialized data.
  /// Usual scenario is when exception is occured somewhere on the remote workstation
  /// and we have to re-create/re-throw the exception on the local machine
  /// </summary>
  /// <param name="info">Serialization info</param>
  /// <param name="context">Serialization context</param>
  protected NegativeNumberException(SerializationInfo info, StreamingContext context)
    : base(info, context) {
  }
}
Run Code Online (Sandbox Code Playgroud)

  • @ kill4silence:添加`using System;`因为在`System`命名空间中定义了`string`的*别名*中的`String`. (2认同)

Ry-*_*Ry- 5

所有异常都是类似于其他异常的类型,如果要定义自定义类型的异常,您实际上必须为它创建一个类:

/* You could also use ArgumentException, etc. */
class NegativeNumberException : Exception {
    …
}

…
Run Code Online (Sandbox Code Playgroud)