c#中異常處理

//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; }
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章