本文讲述了C# try catch?具有很好的参考价值,希望对大家有所帮助。一起跟随六星小编过来看看吧,具体如下:
1、代码放到try快中(try是c#的关键字)。代码运行是,会尝试执行try块内部的语句,如果么有语句发生异常,这些语句将顺序执行下去。直到全部都完成,但是一旦出现异常就跳出try块,执行catch块中的内容。2、try块需要一个或者多个catch块程序捕捉并处理特定类型的异常。
实验步骤:首先通过控制台程序输入一串字符,使用Console.readLine();获取一串字符串数据。
然后使用后int.parse(string s);这个函数将字符串转换为int型数据。
通过查看int.parse(string s);函数定义可以知道他又如下异常。在这里插入代码片
// 异常:// T:System.ArgumentNullException: // s 为 null。 // // T:System.FormatException: // s 的格式不正确。 // // T:System.OverflowException: // s 表示一个小于 System.Int32.MinValue 或大于 System.Int32.MaxValue 的数字。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace tesetData { class Program { static void Main(string[] args) { //try catch的使用 string readString = Console.ReadLine(); int readValue; try { readValue = int.Parse(readString); Console.WriteLine(readValue); } catch (OverflowException) { Console.WriteLine("err:转化的不是一个int型数据"); } catch (FormatException) { Console.WriteLine("err:格式错误"); } catch (ArgumentNullException) { Console.WriteLine("err:null"); } Console.ReadLine(); } } }
异常过滤器:
异常过滤器是c# 6的新功能,它影响异常和catch处理程序的匹配方式,允许指定catch除了程序的额外,处理条件。这些条件采用的形式是when关键字布尔表达式
例如:
catch(OverflowException oe) when (oe.GetType() != typeof(System.FormatException)) { //处理之前没有捕捉除了FormatException之外的所有异常 Console.WriteLine("FormatException之外的所有异常"); }
更多相关技术内容咨询欢迎前往并持续关注六星社区了解详情。
想高效系统的学习Python编程语言,推荐大家关注一个微信公众号:Python编程学习圈。每天分享行业资讯、技术干货供大家阅读,关注即可免费领取整套Python入门到进阶的学习资料以及教程,感兴趣的小伙伴赶紧行动起来吧。
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!