创建我自己的异常c#

时间:2013-12-05 04:13:41

标签: c# exception exception-handling 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);
    }
}

4 个答案:

答案 0 :(得分:51)

Exception只是一个,与.Net中的许多其他类一样。恕我直言,有两个棘手的事情,用户定义的例外:

  1. Exception 继承您的异常类,而不是从过时的 ApplicationException
  2. 继承您的异常类
  3. 在典型案例中,用户定义的例外应该有许多构造函数 - 4
  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) {
      }
    }
    

答案 1 :(得分:5)

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

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

…

答案 2 :(得分:2)

由于来自Exception而不是ApplicationException的.NET 3.0自定义异常should be derived,所以请使用:

public class NegativeNumberException : Exception
{ 
    public NegativeNumberException():base() { } 
    public NegativeNumberException (string message): base(message) { }
}

答案 3 :(得分:1)

您需要声明自定义的异常NegativeNumberException类。

所有自定义异常都是异常的子类,因此从NegativeNumberException

派生Exception

来自MSDN:

  

如果您正在设计需要创建自己的应用程序   例外情况,建议您从中派生自定义异常   异常类。它最初被认为是自定义异常   应该从ApplicationException类派生;但在实践中   这还没有被发现增加显着的价值。更多   信息,请参阅处理例外的最佳实践。   ApplicationException使用HRESULT COR_E_APPLICATION,它具有   值0x80131600。

试试这个:

 public class NegativeNumberException : Exception
        {         


           public NegativeNumberException():base()
            {


            }   

            public NegativeNumberException (string message): base(message)
            {


            }


        }
相关问题