您的位置:首页 > 编程语言 > C#

C#异常处理

2015-07-23 09:09 651 查看
异常提供了一种把程序控制权从某个部分转移到另一个部分的方式。C# 异常处理时建立在四个关键词之上的:trycatchfinallythrow

try:一个 try 块标识了一个将被激活的特定的异常的代码块。后跟一个或多个 catch 块。
catch:程序通过异常处理程序捕获异常。catch 关键字表示异常的捕获。
finally:finally 块用于执行给定的语句,不管异常是否被抛出都会执行。例如,如果您打开一个文件,不管是否出现异常文件都要被关闭。

throw:当问题出现时,程序抛出一个异常。使用 throw 关键字来完成

假设一个块将出现异常,一个方法使用 try 和 catch 关键字捕获异常。try/catch 块内的代码为受保护的代码,使用 try/catch 语法如下所示:

try
{
// 引起异常的语句
}
catch( ExceptionName e1 )
{
// 错误处理代码
}
catch( ExceptionName e2 )
{
// 错误处理代码
}
catch( ExceptionName eN )
{
// 错误处理代码
}
finally
{
// 要执行的语句
}

using System;

namespace ErrorHandlingApplication

{

class DivNumbers

{

int result;

DivNumbers()

{

result = 0;

}

public void division(int num1, int num2)

{

try

{

result = num1 / num2;

}

catch (DivideByZeroException e)

{

Console.WriteLine("Exception caught: {0}", e);

//throw e;

}

finally

{

Console.WriteLine("Result: {0}", result);

}

}

static void Main(string[] args)

{

DivNumbers d = new DivNumbers();

d.division(25, 0);

Console.ReadKey();

}

}

}

实例代码:
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace ConsoleApplication1

{

class Program

{

static string[] eTypes = { "none","simple","index","nested index",};

static void Main(string[] args)

{

foreach (var item in eTypes)

{

try

{

Console.WriteLine("Main() try block reached.");

Console.WriteLine("ThrowException(\"{0}\") called.", eTypes);

}

catch (Exception e)

{

Console.WriteLine("Main() System.IndexOutOfRangeExeception catch" + "block reached Message:\n\"{0}\"", e.Message);

}

catch

{

Console.WriteLine("Main() general catch block reached.");

}

finally

{

Console.WriteLine("Main() finally block reached.");

}

Console.WriteLine();

}

Console.ReadKey();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: