【问题标题】:throwing exception for wrong array length为错误的数组长度抛出异常
【发布时间】:2013-12-14 04:51:46
【问题描述】:

我试图弄清楚如何根据数组的长度抛出异常,但同时,如果长度正确,则能够返回一个值

例如:

 public Complex readInput()
 {
     Complex temp = 0;
     try
     {
          Console.Write("Enter input: ");
          string input = Console.ReadLine();

          String[] cplx= input.Split(' ');
          if (cplx.Length != x)
          {
               throw new IndexOutOfRangeException("INVALID INPUT ENTRY...");
          }

          temp = new Complex(Double.Parse(cplx[0]), Double.Parse(cplx[1]), ...);
     }
     catch (FormatException)
     {
          Console.WriteLine("INVALID INPUT ENTRY...");
     }
     return temp;
 } // end readInput

理想情况下,我只想要 if (opr.Length ...) 和 IndexOutOfRangeException.. 我认为我使用 IndexOutOfRange 不正确。如果数组长度不等于 x(可以是任何 #),有没有办法抛出异常,但如果是,则返回其中的任何内容而不使用 try/catch?

编辑:找出其中的一部分:https://stackoverflow.com/a/20580118/2872988

【问题讨论】:

  • 什么是 x ?你需要定义它吗?!
  • x 只是一个数字。你可以在那里输入任何数字,没关系
  • 你的代码不能正常工作,x应该被赋值,然后在你的catch块中,你可以添加许多catch,它们有很多异常类型。
  • 尝试类似 string Test = cplx[x];那么如果索引不存在,您将得到索引超出范围异常,该异常将由 Catch 处理。

标签: c# arrays exception


【解决方案1】:

我觉得你需要这样扔掉

 public Complex readInput()
 {
     Complex temp = 0;
     try
     {
          Console.Write("Enter input: ");
          string input = Console.ReadLine();

          String[] cplx= input.Split(' ');
          if (cplx.Length >= x)
          {
               throw new IndexOutOfRangeException("INVALID INPUT ENTRY...");
          }

          temp = new Complex(Double.Parse(cplx[0]), Double.Parse(cplx[1]), ...);
     }
     catch (FormatException)
     {
          Console.WriteLine("INVALID INPUT ENTRY...");
     }
     return temp;
 } 

【讨论】:

    【解决方案2】:

    嘿,如果您使用自己的异常描述,代码会更好一些。尝试使用异常(字符串描述)。这样代码看起来会好很多。请记住,例外是提醒程序员某些事情无法正常工作。

            Complex temp = null;
            try
            {
                Console.Write("Enter input: ");
                string input = Console.ReadLine();
    
                String[] cplx = input.Split(' ');
                if (cplx.Length != x)
                    throw new Exception("INVALID INPUT ENTRY...");
    
                temp = new Complex(Double.Parse(cplx[0]), Double.Parse(cplx[1]));
            }
            catch (Exception)
            {
                Console.WriteLine("INVALID INPUT ENTRY...");
            }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-26
    • 2018-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    • 1970-01-01
    相关资源
    最近更新 更多