第三章 异常处理和类 一、异常处理语句 1
什么是异常:在程序运行期间发生的错误或意外(异常是一种错误条件,当代码路径的正常控制流程不符合实际或是不正确时,异常就会发生)
Visu al C#语言的异常处理方法:在程序中加入异常控制代码,提供更为明确的处理结果 3
异常处理语句的使用 (1)格式 1:try -catch 语句 try 语句块中包含可能产生异常的代码,catch 中指定对异常的处理 、 (2)格式 2:try -finally 语句 try 语句块包含可能产生异常的代码 finally 中指定最终都要执行的子语句 与格式 1 比较,程序不提供对异常的处理,只保证 finally 语句块中的代码一定被执行 (3)格式 3:try -catch-finally (常用格式) try 语句块中包含可能产生异常的代码,catch 中指定对异常的处理,finally 中指定最终都要执行的子语句,放在所有 catch 后,只能出现一次 class trycatchstatement { public void test() { try { int b = int
Parse("abc"); } catch (FormatException ex) { Console
WriteLine(ex
Message); } } } class trycatchstatement { public void test() { try { int b = int
Parse("abc"); } finally { Console
WriteLine("执行结束"); } } } class trycatchstatement { public void test() { try { int b = int
Parse("abc"); } catch (FormatExcept