简体   繁体   English

我如何在 c# 中捕获异常?

[英]How I can catch an exception in c#?

I'm having trouble catching an exception in c#. I want to convert numbers from decimal systems to (other) systems, so for example, if the user enters dec num, which contains other characters ('a', 'b', 'c' etc.) program will show an error message.我无法捕获 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!");
}

Thank you!谢谢!

Exceptions are designed for exceptional situations ;异常是为异常情况而设计的; here you have a user input validation (no need in such means like exceptions);在这里你有一个用户输入验证(不需要像例外这样的方式); a simple loop ( foreach ) and if will be enough:一个简单的循环( 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 
   }

There are two articles on exception handling, that I link often:有两篇关于异常处理的文章,我经常链接:

You are in the non-eviable position of writing your own parsing and Exception throwing code.您处于编写自己的解析和异常抛出代码的不可逃避的 position 中。 But it might actually be unessesary - .NET has support for innumerable Number formats and Numbering Systems.但它实际上可能是不必要的 - .NET 支持无数的数字格式和编号系统。 Hex to Decimal can be done in 2 commands: https://learn.microsoft.com/en-us/do.net/csharp/programming-guide/types/how-to-convert-between-hexadecimal-strings-and-numeric-types#example-2十六进制到十进制可以通过 2 个命令完成: https://learn.microsoft.com/en-us/do.net/csharp/programming-guide/types/how-to-convert-between-hexadecimal-strings-and-数字类型#example-2

It seems like you are trying to reinvent Int.TryPrase() and are doing just about everything wrong.似乎您正在尝试重新发明 Int.TryPrase() 并且几乎做错了所有事情。 You should try to use existing parse functions, before you try to reinvent the wheel.在尝试重新发明轮子之前,您应该尝试使用现有的解析函数。

What you wrote does not look like a proper TryParse function, where you can catch the Vexing exceptions but still communicate that they happened.您写的内容看起来不像正确的 TryParse function ,您可以在其中捕获令人烦恼的异常,但仍然表明它们发生了。 And what you do catch is also way to wide.而且您所捕获的也很广泛。 There seem to be fundamental design flaws, too many to simply fix.似乎存在基本的设计缺陷,太多无法简单修复。

If you are dead set on reinventing that wheel, I would advise first and foremost to read the two articles I linked, so you do not make the common Exception Handling mistakes.如果您执意要重新发明那个轮子,我会首先建议您阅读我链接的两篇文章,这样您就不会犯常见的异常处理错误。 I did once write a TryParse approximation for someone stuck on Framework 1.1.我曾经为卡在 Framework 1.1 上的某个人写过 TryParse 近似值。 This might give you some ideas:这可能会给你一些想法:

//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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM