using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 异常1
{
class Program
{
static void Main(string[] args)
{
try //可能会发生异常的代码
{
int i = Convert.ToInt32("123"); //“abc”是出现异常
//发生异常之后的语句不会执行
Console.WriteLine("Convert 之后");
}
catch (System.Exception ex) //当try中出现错误时,执行catch中的代码 处理异常
{
Console.WriteLine("数据错误"+ ex.Message +"异常堆栈" + ex.StackTrace);
//ex.Message :错误的原因
//ex.StackTrace: 异常堆栈 最后一行显示异常的位置
}
try
{
string desc = GetAgeDesc(-1);
Console.WriteLine(desc);
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message );
Console.WriteLine(ex.StackTrace);
}
//catch中的代码执行完后 继续执行
Console.WriteLine("readkey 之前");
Console.ReadKey();
}
//在自己的程序中 throw exception对象
static string GetAgeDesc(int age)
{
if (age >= 0 && age <= 3)
{
return "婴幼儿";
}
else if (age > 3 && age <= 18)
{
return "青少年";
}
else if (age > 19 && age <= 150)
{
return "成年人";
}
else if(age < 0)
{
throw new Exception("您来自反物质世界吧");
}
else
{
throw new Exception("您见过老佛爷吧");
}
}
}
}
/* 如果不处理异常 就会在程序运行时报错
*
*
* 不要吃掉异常,一般情况下不需要处理异常
*
* 把整个程序用try catch 匡起来是不好的
*
* 什么时候使用try catch 这个点我不是很明白
*/
C#学习笔记(十六) --异常
最新推荐文章于 2023-12-28 10:38:23 发布