在输入两个数字进行相加的操作时,若输入的内容不符合要求会出现异常,在C#程序中可用try-catch-finally语句处理异常,具体代码为:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace trysample_10._12_
{
class Program
{
static void Main(string[] args)
{
calculator c = new calculator();
int r = c.add("120", "240");
Console.WriteLine(r);
}
}
class calculator
{
public int add(string str1,string str2)
{
int x = 0;
int y = 0;
bool haserror = false;
try
{
x = int.Parse(str1);
y = int.Parse(str2);
}
catch(ArgumentNullException ane)
{
Console.WriteLine(ane.Message);
haserror = true;
}
catch(FormatException fe)
{
Console.WriteLine(fe.Message);
haserror = true;
}
catch(OverflowException oe)
{
Console.WriteLine(oe.Message);
haserror = true;
}
finally
{
if(haserror==true)
{
Console.WriteLine("The program has error!");
}
else
{
Console.WriteLine("Right!");
}
}
int result = x + y;
return result;
}
}
}
若输入内容正确,结果为:
若输入内容不正确,程序会在命令行窗口报错并显示具体错误原因,结果为:

版权声明:本文为weixin_44302503原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。