c#异常处理示例分享

时间:2021-05-20

复制代码 代码如下:
using System;
using System.Collections.Generic;
using System.Linq; using System.Text;
//2014.3.14
namespace _6.异常
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Convert之前");
int a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Convert之后");
}
catch (Exception ex)
{
Console.WriteLine("输入错误:"+ex.Message+"异常堆栈:"+ex.StackTrace);
}

try
{
Console.WriteLine("请输入你的年龄:");
int s = Convert.ToInt32(Console.ReadLine());
string desc = GetAgeDesc(s);
Console.WriteLine(desc);
}
catch (Exception ex)
{
Console.WriteLine("数据错误,"+ex.Message);
}
Console.ReadKey();
}

static string GetAgeDesc(int age)
{
if (age >= 0 && age <= 3)
{
return "婴幼儿";
}
else if (age > 3 && age < 18)
{
return "青少年";
}
else if (age >=18 && age < 60)
{
return "成年人";
}
else if (age >= 60 && age < 100)
{
return "老年人";
}
else
{
throw new Exception("自己创建的ex.Message");
}
}
}
}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章