当前位置: 首页 > 科技观察

C#如何创建用户定义的异常?

时间:2023-03-16 11:31:00 科技观察

概述异常是程序执行过程中出现的问题。C#中的异常是对程序运行时出现的特殊情况的响应,例如试图被零除。异常提供了一种将控制从程序的一部分转移到另一部分的方法。C#异常处理基于四个关键字:try、catch、finally和throw。try:try块标识将为特定异常激活的代码块。后跟一个或多个catch块。catch:程序通过异常处理器捕获异常。catch关键字表示捕获异常。finally:finally块用于执行给定的语句,无论是否抛出异常。比如你打开一个文件,不管有没有异常,这个文件都会被关闭。throw:当出现问题时,程序抛出异常。这是使用throw关键字完成的。自定义异常您还可以定义自己的异常。用户定义的异常类派生自ApplicationException类。usingSystem;namespaceUserDefinedException{classTestTemperature{staticvoidMain(string[]args){Temperaturetemp=newTemperature();try{temp.showTemp();}catch(TempIsZeroExceptione){Console.WriteLine("TempIsZeroException:{0}",e.Message);}Console.ReadKey();}}}publicclassTempIsZeroException:ApplicationException{publicTempIsZeroException(stringmessage):base(message){}}publicclassTemperature{inttemperature=0;publicvoidshowTemp(){if(temperature==0){throw(newTempIsZeroException("ZeroTemperaturefound"));}else{Console.WriteLine("Temperature:{0}",temperature);}}}当上面的代码被编译和执行时,会产生如下结果:TempIsZeroException:ZeroTemperaturefoundthrowsobjectifexception你可以抛出直接或间接派生自System.Exception类的对象。可以在catch块中使用throw语句抛出当前对象,如下所示:Catch(Exceptione){...Throwe}【编者推荐】为什么光通信发展不如5G?快车道上,各种智能技术看好Linkerd2.10(StepbyStep)(4)如何配置外部Prometheus实例勒索攻击频发大厂纷纷中招如何保护企业?IDC发布《2021 年第一季度中国IT安全硬件市场跟踪报告》