c#中异常处理

来源:互联网 发布:网络作家如何挣钱 编辑:程序博客网 时间:2024/06/07 17:02

//1 try , catch finally
//什么是异常?异常实际上是程序中错误导致中断了正常的指令流的一种事件.
//1 try , catch finally
//int[] array = { 1, 2, 32, 4 };
try
{
Console.WriteLine(array[4]);
}
catch (Exception)
{
throw;//这里会抛出异常(如果删除catch,异常不会显示,直接运行下面的程序,反之,显示异常,继续运行下面的程序)
}
Console.WriteLine(“例如这就是下面的程序”);
Console.WriteLine(“*******”);
//如果多个异常
//try //try块里是捕捉的异常
//{
// Console.WriteLine(array[4]);
// int a = 10;
// int b = 0;
// Console.WriteLine(a / b);
// Console.WriteLine(“1234567890”);
//}
catch (Exception)
{
throw;//这里只会抛出第一个异常(如果删除catch,异常不会显示,直接运行下面的程序,反之,显示异常,继续运行下面的程序)
}
Console.WriteLine(“*******”);
//根据情况处理异常
//try //try块里是捕捉的异常
//{
// Console.WriteLine(array[4]);
// int a = 10;
// int b = 0;
// Console.WriteLine(a / b);
// Console.WriteLine(“1234567890”);
//}
//例如这个是DivideByZeroException分母为0异常
//catch (DivideByZeroException) //catch块里是处理异常
//{
// Console.WriteLine(“/0”);
//}
//catch (IndexOutOfRangeException)
//{
// Console.WriteLine(“数组越界了,做xxx处理”);
//}
//finally
//{
// Console.WriteLine(“都会执行”);
//}
Console.WriteLine(“*******”);
// 抛出异常
try
{
PrintAge();
}
catch (MyException my)
{
Console.WriteLine(“”);
}
Console.WriteLine(“324567890-=”);
}
static void PrintAge()
{
Student s = new Student();
int age = Int32.Parse(Console.ReadLine());
if (age < 18)
{
//抛出异常
throw new MyException(“你这个孩子未成年”);
}
s.Age = age;
Console.WriteLine(s.Age);
}
}
class MyException : Exception
{

public MyException(string message):base(message)
{

}
}
class Student
{
int _age;
string _name;
public int Age { get => _age; set => _age = value; }
}
}

原创粉丝点击