C#各种异常处理方式.NET的异常处理机制用来发现、处理运行时错误。如果开发人员没有提供异常的处理机制,就默认采用.NET的机制。
通常使用try...catch...finally捕获异常。
try
{
//有可能发生异常
}
catch(Exception ex)
{
//处理异常
}
finally
{
//清理
}
○ 如果没有异常发生,就直接到finally语句块中。○ finally语句块是必须执行的○ 这里的catch和finally语句块是可选的。try语句块后面可以跟1个或多个catch语句块,try语句块后面可以直接跟finally语句块。○ Exception是所有异常的基类
□ 使用.NET默认异常处理机制捕获异常
class PRogram
{
static void Main(string[] args)
{
int a = 0;
int result = 100/a;
Console.WriteLine(result);
Console.ReadKey();
}
}
□ 使用try...catch手动捕获异常
class Program
{
static void Main(string[] args)
{
int a = 0;
int result = 0;
try
{
result = 100/a;
Console.WriteLine("这里不会执行");
}
catch (DivideByZeroException exception)
{
Console.WriteLine("出现异常");
}
Console.WriteLine(result);
Console.ReadKey();