异常提供了一种将控制从程序的一个部分转移到另一个部分的方法,C#异常处理基于四个关键字:try、catch、finally和throw。
try - TRY为其激活特定异常的代码块,后面跟着一个或多个catch块。
catch - catch关键字指示捕获异常。
finally - Finally块用于执行给定的一组语句,无论是否引发异常。例如,如果打开一个文件,则无论是否引发异常,都必须关闭该文件。
throw - 通过使用抛出throw关键字向上抛出异常。
假设块引发异常,则方法使用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块在不同的情况下引发多个异常。
C#中的异常类主要直接或间接从System.Exception类派生。System.Exception类派生异常类是System.ApplicationException和System.SystemException。
System.ApplicationException - 支持应用程序生成的异常,因此,程序员定义的异常应该派生自此类。
System.SystemException - 是所有预定义系统异常的基类。
下表提供了从Sytem.SystemException类-派生的一些预定义异常类
Sr.No. | Exception Class & 描述 |
---|---|
1 | System.IO.IOException 处理I/O错误。 |
2 | System.IndexOutOfRangeException 数组索引超出范围时生成的错误。 |
3 | System.ArrayTypeMismatchException 处理类型与数组类型不匹配时生成的错误。 |
4 | System.NullReferenceException 处理引用空对象产生的错误。 |
5 | System.DivideByZeroException 处理因被除数为零而产生的错误。 |
6 | System.InvalidCastException 处理类型转换期间生成的错误。 |
7 | System.OutOfMemoryException 处理由于可用内存不足而产生的错误。 |
8 | System.StackOverflowException 处理堆栈溢出生成的错误。 |
C#以try和catch块的形式提供了异常处理的解决方案,使用这些块,核心程序语句与错误处理语句分开,以下是在被零除条件发生-时引发异常的示例
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 }
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)