c# - 如何在 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!");
}
谢谢!
解决方案
例外是为特殊情况设计的;在这里你有一个用户输入验证(不需要像异常这样的方式);一个简单的循环 ( 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
}
推荐阅读
- sql-server - SQL Server 存储过程传递日期参数
- python - pd.to_csv 导致意外的行满空单元格(但将索引名称保持在同一行)
- c++ - 在 g++ 中同时使用静态和动态链接库
- javascript - AJAX 调用后,我的 JS 代码在我刷新页面之前不会加载
- bash - 如何使用 BASH 以随机顺序生成给定范围之间的数字。每个数字只能出现一次
- r - 使用 RMarkdown 启动 renv::activate() 会导致 R 崩溃
- android - 三个按钮,三个不同的动作/输出
- reactjs - React Native - npm 错误:超出最大调用堆栈大小
- azure - azure appInsights 从 url 获取字符串的一部分并将其显示在名称列中
- listview - 如何在 Odoo 13 企业版中使用 Studio 汇总字段并在列表视图中显示?