一般来说, 你的程序会在出错时隐式地生成异常. 但是如果想要显式地抛出异常, 可以使用throw语句.
如果您没有捕获您程序产生的异常, 这个异常将会由通用异常处理程序处理. 该程序会产生一个对话窗口. (如图所示).

可以使用try 对可能出现问题的代码进行分区, 使用catch对可能出现问题的代码进行处理. 使用finally来写那些无论是否发生了异常都会继续运行的代码.
try需要一个或多个关联的catch块(每种catch块处理一个异常), 或是一个finally块, 或是两者兼有.
在多个关联的catch块中, 计算顺序为从上到下. 但是针对每个引发的异常, 仅执行一个catch块. 也就是说, 每个引发的异常将执行遇到的第一个符合所引发异常的确切类型或者基类的catch块, 这提示我们将最具体的异常写在最上方.
编译器生成的异常往往派生自SystemException类. 具体的异常名称可以参阅这里.
以下是一个异常处理的语法格式示例:
try
{
// Code to try goes here.
}
catch (SomeSpecificException ex)
{
// Code to handle the exception goes here.
}
finally
{
// Code to execute after the try (and possibly catch) blocks
// goes here.
}
可以添加when关键字作为异常筛选器.
when可以在上下文中指定筛选条件. 可在catch子句中使用when关键字来指定一个条件,此条件必须为 true,才能执行特定异常的处理程序。 语法为:
catch (ExceptionType [e]) when (expr)
下面是一个具体的例子:
using System;
class GetIndex {
static public int GetArrayElem(int[] arr,int index) {
try {
return arr[index];
}
catch (IndexOutOfRangeException e) when (index < 0){
//throw new ArgumentOutOfRangeException("Parameter index cannot be negative.", e);
Console.WriteLine("Parameter index cannot be negative.");
return -1;
}
catch (IndexOutOfRangeException e) {
//throw new ArgumentOutOfRangeException("Parameter index cannot be greater than the array size.", e);
Console.WriteLine("Parameter index cannot be greater than the array size.");
return -1;
}
}
}
class Application {
public static void Main(string[] args) {
int[] arr;
arr = new int[10];
GetIndex.GetArrayElem(arr, -1);
GetIndex.GetArrayElem(arr, 10);
}
}
System.Exception类, 即可以使用throw来抛出异常.由于c#是个面向对象的语言, 所以异常自然也是一个对象啦~具体来说, 异常都是一个个类. 系统生成的异常派生自类System.Exception, 而用户定义异常时, 可以派生自System.ApplicationException类.
该类有ApplicationException(String)这样的构造函数, 您可以使用它来指定异常的文本.
以下是一个例子:
using System;
public class ElemNotFound : ApplicationException {
public ElemNotFound(string str):base(str) {
}
}
class Application {
public static void Main(string[] args) {
ElemNotFound e = new ElemNotFound("Can not found element");
throw e;
}
}