把可能出危险的代码包在 try 里。如果出了事,catch 会接住它。
try
{
int a = 10;
int b = 0;
int c = a / b; // 危险!除以零!
Console.WriteLine("结果是:" + c);
}
catch (DivideByZeroException ex) // 专门接“除以零”的招
{
Console.WriteLine("哎呀!不能除以零!");
Console.WriteLine("错误详情:" + ex.Message);
}
catch (Exception ex) // 接住所有其他类型的招(万能盾牌)
{
Console.WriteLine("发生了未知的错误!");
}
不管有没有出事,最后都要做的事情(比如收剑回鞘、关闭文件)。
try
{
// 打开藏宝箱...
}
catch
{
// 遇到机关...
}
finally
{
// 无论有没有拿到宝藏,都要把箱子盖上!
Console.WriteLine("清理现场...");
}
try-catch!
编写一个程序,让用户输入一个数字。如果用户输入的不是数字(比如输入了 "abc"),程序不要崩溃,而是温柔地提示“请输入正确的数字”。
try
{
Console.Write("请输入年龄:");
string input = Console.ReadLine();
int age = int.Parse(input); // 这里可能炸
Console.WriteLine("你的年龄是:" + age);
}
catch (FormatException)
{
Console.WriteLine("大侠,请输入数字,别输入乱码!");
}