try:尝试执行try中的代码,如果出现异常会停止执行跳转到catch中
catch:处理异常 反馈异常的问题 可以自行定义反馈’
finally:无论是否出现异常都会执行finally的代码
举例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
class Program
{
static void Main(string[] args)
{
//尝试执行try中的代码
//如果出现异常会停止执行跳转到catch中
try
{
Console.WriteLine("请输入数字");
int a = Convert.ToInt32(Console.ReadLine());
}
//catch处理异常 反馈异常的问题
catch(Exception Ex)
{
Console.WriteLine(Ex.Message);
}
//无论是否出现异常都会执行finally的代码
finally
{
Console.WriteLine("程序结束");
}
Console.ReadLine();
}
}
}
运行结果:
- 如果输入正常的数字那么不会报错 也不会有反馈
- 如果输入的不是数字,那么会给予反馈”输入的字符串格式不正确“
- 同理如果数组越界等也会给予”数组越界“的反馈
总结:
try-catch-finally
可以用来处理异常,处理不确定问题,避免错误的发生