如何在C#中捕获异常?

时间:2020-04-15 11:36:18

标签: c# try-catch

我在捕捉C#中的异常时遇到麻烦。我想将数字从十进制转换为(其他)系统,例如,如果用户输入dec num,该数字包含其他字符(“ a”,“ b”,“ c”等),程序将显示错误消息

try
{
    string numbers = "0123456789abcdef";
    for (int i=0; i<txt.Length; i++)
    {
        for (int j=0; j<16; i++)
        {
            if (txt[i] == numbers[j] && j >= 10)
                throw new Exception();
        }
    }
}
catch (Exception)
{
    MessageBox.Show("Error!");
}

谢谢!

2 个答案:

答案 0 :(得分:1)

例外专为例外情况设计;这里您有一个用户输入 validation (不需要像异常这样的方式);一个简单的循环(foreach)和if就足够了:

 foreach (char c in txt)
   if (c < '0' || c > '9') {
     MessageBox.Show("Error!");

     break; // at least one error, let's skip further validation 
   }

答案 1 :(得分:0)

我经常链接两篇有关异常处理的文章:

您处于编写自己的解析和异常引发代码的不可避免的位置。但这实际上可能不是必需的-.NET支持无数的数字格式和编号系统。十六进制到十进制可以用2个命令完成:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/how-to-convert-between-hexadecimal-strings-and-numeric-types#example-2

似乎您正在尝试重塑Int.TryPrase(),并且几乎在做所有错误的事情。在尝试重新发明轮子之前,应该尝试使用现有的解析函数。

您编写的内容看起来不像是一个正确的TryParse函数,您可以在其中捕获Vexing异常,但仍可以传达它们的发生。您所做的事情也很广泛。似乎存在一些基本的设计缺陷,太多无法简单修复。

如果您对重新发明轮子一无所知,我建议您首先阅读我链接的两篇文章,这样您就不会犯常见的“异常处理”错误。我曾经为卡在Framework 1.1上的人写过TryParse近似值。这可能会给您一些想法:

//Parse throws ArgumentNull, Format and Overflow Exceptions.
//And they only have Exception as base class in common, but identical handling code (output = 0 and return false).

bool TryParse(string input, out int output){
  try{
    output = int.Parse(input);
  }
  catch (Exception ex){
    if(ex is ArgumentNullException ||
      ex is FormatException ||
      ex is OverflowException){
      //these are the exceptions I am looking for. I will do my thing.
      output = 0;
      return false;
    }
    else{
      //Not the exceptions I expect. Best to just let them go on their way.
      throw;
    }
  }

  //I am pretty sure the Exception replaces the return value in exception case. 
  //So this one will only be returned without any Exceptions, expected or unexpected
  return true;
}