c# 异常处理
嵌套
异常嵌套可一起检查多个异常,其中一环出现异常,便停止排查余下异常
1 public class TryCatch 2 { 3 public void Test1(int a ) 4 { 5 try 6 { 7 int i = 1 / a; 8 9 Console.WriteLine(i); 10 try 11 { 12 int j = i + 1; //异常嵌套 13 Console.WriteLine(j); 14 } 15 catch (IndexOutOfRangeException e) 16 { 17 Console.WriteLine(e.Message); 18 Console.WriteLine(e.StackTrace); 19 20 21 } 22 } 23 catch(Exception e ) //当不知道异常种类时用Exception 24 { 25 Console.WriteLine(e.Message); 26 } 27 finally 28 { 29 Console.WriteLine("结果"); 30 } 31 32 } 33 }
多重异常处理
Argument三个异常为参数相关,需先定义一下

1 public class Exceptions 2 { 3 public static void Text1(string name,int age,string sex) 4 { 5 if (string .IsNullOrWhiteSpace(name)) 6 { 7 throw new ArgumentNullException("name"); 8 } 9 if (sex!="boy" &&sex!= "girl") 10 { 11 throw new ArgumentException("sex"); 12 } 13 if (age>=150 || age <=0) 14 { 15 throw new ArgumentOutOfRangeException("age"); 16 } 17 Console.WriteLine(name + age + sex); 18 } 19 }
1 2 try 3 { 4 Exceptions.Text1("tt", 23, "boy"); 5 Console.WriteLine("无异常"); 6 } 7 8 catch (ArgumentNullException e) 9 { 10 Console.WriteLine(e.Message); 11 Console.WriteLine(e.StackTrace); 12 } 13 catch (ArgumentOutOfRangeException e) 14 { 15 Console.WriteLine(e.Message); 16 Console.WriteLine(e.StackTrace); 17 } 18 catch (ArgumentException e) 19 { 20 Console.WriteLine(e.Message); 21 Console.WriteLine(e.StackTrace); 22 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器