《C#中异常处理语句的使用和调试》由会员分享,可在线阅读,更多相关《C#中异常处理语句的使用和调试(7页珍藏版)》请在金锄头文库上搜索。
1、1.异常处理语句的使用常用的异常处理语句a.throwb.try.catchb.try.catch.finally详细讲解(throw )throw 语句用于主动引发一个异常,即在特定的情形下自动抛出异常。基本格式如下:throw ExObject(ExObject:所要抛出的异常对象,这个异常对象是派生自 System.Exception 类的类对象)例:class Programclass testpublic int MyInt(string a, string b)int int1;int int2;int num;int1 = int.Parse(a);int2 = int.Pars
2、e(b);if (int2 = 0)throw new DivideByZeroException();return 0;elsenum = int1 / int2;return num;static void Main(string args)while (true)Console.WriteLine(请输入分子:);string str1 = Console.ReadLine();Console.WriteLine(请输入分母:); string str2 = Console.ReadLine();test tt = new test();Console.WriteLine(分子除以分母的
3、值:+tt.MyInt(str1,str2);运行结果:详细讲解(try.catch)格式:try被监控的代码catch(异常类名 异常变量名)异常处理例:static void Main(string args)tryobject obj = null;int N = (int)obj;catch(Exception ex) Console.WriteLine(捕获异常:+ex);Console.ReadLine();运行结果:详细讲解(try.catch.finally)try被监控的代码catch(异常类名 异常变量名)异常处理.finally程序代码例:static void Main
4、(string args)string str = c#编程词典;object obj = str;tryint i = (int)obj;catch (Exception ex)Console.WriteLine(ex.Message);finallyConsole.WriteLine(程序执行完毕。);Console.ReadKey(); 运行结果:2.常用的调试操作断点操作断点是一个信号,它通知调试器在某个特定点上暂时将程序执行挂起。a.插入断点第一种方法:第二种方法:第三种方法: b.删除断点同上,类似开始、中断和停止程序的执行a 开始执行.* 调试-启动调试;* 在源代码窗口右击可执
5、行某行,选择“运行到光标处”。*b.中断执行* * c.停止执行选择调试-停止调试单步执行F11 键执行“逐语句”F10 键执行“逐过程”shift+F10 键执行“跳出”3.实践项目使用异常处理语句捕获数据库连接异常static void Main(string args) SqlConnection sqlcon = new SqlConnection(Data Source=(local);Database=master;uid=sa;pwd=root;);trysqlcon.Open();Console.WriteLine(连接成功!);catch(SqlException ex)Console.WriteLine(ex.Message);Console.ReadKey();通过插入断点查看局部变量的值