异常(例外)是在执行程序期间出现的问题。 c# 异常是对程序运行时出现的异常情况的响应,例如:除以零的算术运算。
异常提供了将控制从程序的一个部分转移到另一个程序的方法。 c# 异常处理建立在四个关键字上:try
,catch
,finally
和throw
。
try
块标识一个特定异常被激活的代码块。try
块之后有一个或多个catch
块。catch
关键字表示捕获异常。finally
块用于执行给定的一组语句,无论抛出异常还是抛出异常。例如,如果打开文件,则不管是否引发异常,都必须关闭该文件。throw
关键字完成的。假设一个块引发异常,一个方法使用try
和catch
关键字的组合来捕获异常。try/catch
块放在可能会产生异常的代码周围。try/catch
块中的代码被称为受保护代码,并且使用try/catch
的语法如下所示:
try
{
// statements causing exception
}catch( exceptionname e1 ){
// error handling code
}catch( exceptionname e2 ){
// error handling code
}catch( exceptionname en ){
// error handling code
}finally{
// statements to be executed
}
可以列出多个catch
语句来捕获不同类型的异常,以防try
块在不同情况(case
)下引发多个异常。
c# 异常由类表示。 c# 中的异常类主要直接或间接地从system.exception
类派生。 从system.exception
类派生的一些异常类是system.applicationexception
和system.systemexception
类。
system.applicationexception
类支持应用程序生成的异常。因此,程序员定义的异常应该从这个类派生出来。
system.systemexception
类是所有预定义系统异常的基类。
下表列出了一些从system.systemexception
类派生的一些预定义的异常类:
异常类 | 描述 |
---|---|
system.io.ioexception | 处理i/o 错误 |
system.indexoutofrangeexception | 处理当方法引用数组索引超出范围时生成的错误。 |
system.arraytypemismatchexception | 处理类型与数组类型不匹配时生成的错误。 |
system.nullreferenceexception | 处理从引用空(null )对象而产生的错误。 |
system.dividebyzeroexception | 处理除以零产生的错误。 |
system.invalidcastexception | 处理类型转换过程中产生的错误。 |
system.outofmemoryexception | 处理由于空闲内存不足而产生的错误。 |
system.stackoverflowexception | 处理由于空闲内存不足而产生的错误。 |
system.stackoverflowexception | 处理堆栈溢出产生的错误。 |
c# 以try
和catch
块的形式提供了异常处理的结构化解决方案。使用这些块,核心程序语句与错误处理语句分离。
这些错误处理块使用try
,catch
和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);
}
finally
{
console.writeline("result: {0}", result);
}
}
static void main(string[] args)
{
divnumbers d = new divnumbers();
d.division(25, 0);
console.readkey();
}
}
}
当上述代码被编译并执行时,它产生以下结果:
exception caught: system.dividebyzeroexception: attempted to divide by zero.
at ...
result: 0
您也可以定义自己的异常。用户定义的异常类派生自exception
类。以下示例演示如何创建一个自定义异常:
using system;
namespace userdefinedexception
{
class testtemperature
{
static void main(string[] args)
{
temperature temp = new temperature();
try
{
temp.showtemp();
}
catch(tempiszeroexception e)
{
console.writeline("tempiszeroexception: {0}", e.message);
}
console.readkey();
}
}
}
public class tempiszeroexception: exception
{
public tempiszeroexception(string message): base(message)
{
}
}
public class temperature
{
int temperature = 0;
public void showtemp()
{
if(temperature == 0)
{
throw (new tempiszeroexception("zero temperature found"));
}
else
{
console.writeline("temperature: {0}", temperature);
}
}
}
当上述代码被编译并执行时,它产生以下结果:
tempiszeroexception: zero temperature found
如果直接或间接派生自system.exception
类,则可以抛出一个对象。可以在catch
块中使用throw
语句将当前对象抛出:
catch(exception e)
{
...
throw e
}