首页 > 解决方案 > 如何在 C# 中捕获异常?

问题描述

我无法在 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!");
}

谢谢!

标签: c#try-catch

解决方案


例外是为特殊情况设计的;在这里你有一个用户输入验证(不需要像异常这样的方式);一个简单的循环 ( 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 
   }

推荐阅读