轻松学习C#的异常处理
异常是程序运行中发生的错误,异常处理是程序设计的一部分。错误的出现并不总是编写应用程序者的原因,有时候应用程序会因为终端用户的操作发生错误。无论如何,在编写程序前,都应该预测应用程序和代码中出现的错误。一般良好的编程规范也会避免一些不必要的程序错误的出现。 <span style="font-size:18px;">using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Text { class Program { static void Main(string[] args) { int[] nums = { 1,2,3,4,5,6,7,8,9 }; try//捕获异常 { for (int i = 0; i <= nums.Length; i++)//遍历数组所有元素 { Console.Write(nums[i] + " "); } } catch (Exception a)//访问异常对象 { Console.Write(a.Message);//输出异常错误 } Console.WriteLine(); Console.ReadLine(); } } }</span> 输出的结果为:
由于数据元素的索引是从0开始的,for语句遍历数组元素时,用了“小于或等于”,正好多遍历一次,所以出现索引越界。 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Text { class Program { static void Main(string[] args) { int[] nums = { 4,12,10 }; try//捕获异常 { for (int i = 0; i < nums.Length; i++) { int valude = 0; valude = 240 / nums[i]; Console.WriteLine("240/{0}={1}",nums[i],valude); } } catch (Exception a)//访问异常对象 { Console.WriteLine(a.Message);//输出异常错误 } finally { Console.WriteLine("有没有异常我都会运行"); } Console.WriteLine(); Console.ReadLine(); } } } 输出的结果为: 三、引发异常 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Text { class Program { static void Main(string[] args) { string str = "string"; try { int returnInt; returnInt = Program.ConvertStringToInt(str);//调用转换 Console.Write(returnInt); } catch (FormatException a) { Console.WriteLine(a.Message); } Console.ReadLine(); } private static int ConvertStringToInt(string str)//定义转换函数 { int intNum = 0; try { intNum = Convert.ToInt32(str); return intNum; } catch { throw new FormatException("转换错误");//引发异常 } } } } 输出的结果为: 四、自定义异常类 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Text { class MyException : SystemException { }//声明异常 class Program { static void Main(string[] args) { try { Console.WriteLine("引发异常前我是被执行的");//引发异常前的提示 throw new MyException(); Console.WriteLine("因为已经引发异常,所以我不能被执行"); } catch (MyException) { Console.WriteLine("引发异常"); } Console.ReadLine(); } } } 输出的结果为: 以上就是本文的全部内容,希望对大家的学习有所帮助。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |