您现在的位置: 365建站网 > 365文章 > C#中try catch finally 执行顺序 获取错误信息和错误行数的方法

C#中try catch finally 执行顺序 获取错误信息和错误行数的方法

文章来源:365jz.com     点击数:1733    更新时间:2018-06-29 09:38   参与评论

C#中try catch finally 用法


cefc1e178a82b901b258f2de748da9773812ef62.jpg



1、将预见可能引发异常的代码包含在try语句块中。 

2、如果发生了异常,则转入catch的执行。

catch有几种写法:

catch  这将捕获任何发生的异常。

catch(Exception e)  这将捕获任何发生的异常。另外,还提供e参数,你可以在处理异常时使用e参数来获得有关异常的信息。

catch(Exception的派生类 e)  这将捕获派生类定义的异常,例如安卓中文网,我想捕获一个无效操作的异常,可以如下写:

catch(InvalidOperationException e) {     .... }  这样,如果try语句块中抛出的异常是InvalidOperationException,将转入该处执行,其他异常不处理。  

catch可以有多个,也可以没有,每个catch可以处理一个特定的异常。.net按照你catch的顺序查找异常处理块,如果找到,则进行处理,如果找不到,则向上一层次抛出。如果没有上一层次,则向用户抛出,此时,如果你在调试,程序将中断运行,如果是部署的程序,将会中止。   如果没有catch块,异常总是向上层(如果有)抛出,或者中断程序运行。  

3、finally 

finally可以没有,也可以只有一个。无论有没有发生异常,它总会在这个异常处理结构的最后运行。即使你在try块内用return返回了,在返回前,finally总是要执行,这以便让你有机会能够在异常处理最后做一些清理工作。如关闭数据库连接等等。 

注意:如果没有catch语句块,那么finally块就是必须的。  如果你不希望在这里处理异常,而当异常发生时提交到上层处理,但在这个地方无论发生异常,都要必须要执行一些操作,就可以使用try finally, 很典型的应用就是进行数据库操作: 用下面这个原语来说明:

</>code

  1. try
  2. {     
  3. DataConnection.Open();    
  4. DataCommand.ExecuteReader();    
  5. ...    
  6. return;
  7. }
  8. finally
  9. {     
  10. DataConnection.Close();
  11. }

无论是否抛出异常,也无论从什么地方return返回,finally语句块总是会执行,这样你有机会调用Close来关闭数据库连接(即使未打开或打开失败,关闭操作永远是可以执行的),以便于释放已经产生的连接,释放资源。   

顺便说明,return是可以放在try语句块中的。但不管在什么时机返回,在返回前,finally将会执行。

小结 

</>code

  1. try
  2. {
  3. //执行的代码,其中可能有异常。一旦发现异常,则立即跳到catch执行。否则不会执行catch里面的内容
  4. catch
  5. {
  6. //除非try里面执行代码发生了异常,否则这里的代码不会执行
  7. finally
  8. {
  9. //不管什么情况都会执行,包括try catch 里面用了return ,可以理解为只要执行了try或者catch,就一定会执行 finally  
  10. }

 vb.net写法:

</>code

  1. Try
  2. Catch ex As Exception
  3.      MsgBox(ex.Message)
  4. End Try


完整程序代码如下:

</>code

  1. using System; 
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace _3_16
  5. class Program
  6. static void ProcessString(string str)
  7. if (str == null)
  8. {  throw new ArgumentNullException();
  9. }
  10. static void Main()
  11.  Console.WriteLine("输出结果为:");
  12. try
  13. string str = null;
  14. ProcessString(str);
  15. catch (ArgumentNullException e)
  16. Console.WriteLine("{0} First exception.", e.Message);
  17. catch (Exception e)
  18. Console.WriteLine("{0} Second exception.", e.Message);
  19. }
  20. }
  21. }
  22. }


C#中try catch finally的执行顺序


1.首先明确一点,就是不管怎样,finally一定会执行,即使程序有异常,并且在catch中thorw 了 ,finally还是会被执行。

2.当try和catch中有return时,finally仍然执行。

3.finally是在return后面的表达式运算完之后执行的,在执行完return时 ,程序并没有跳出,而是进入到finally中继续执行,

  如果在finally如果对返回值进行了重新赋值,分为两种情况:

(1)当返回值是值类型(包括string类型,虽然是引用类型,这是特殊的个例)时,返回的值不受影响,

        就是在trycatch时,返回的值已经确定了。

(2)当返回值是引用类型时,会影响到返回值,eg:  

</>code

  1. public static string[] TestYinYong()
  2.      {
  3.          string[] arr = { "one", "two" };
  4.          try
  5.          {
  6.              throw new Exception();
  7.          }
  8.          catch (Exception)
  9.          {
  10.              return arr;
  11.          }
  12.          finally
  13.          {
  14.              arr[1] = "three";
  15.          }
  16.      }

   


此时返回的值是:{ "one", "three" };

4.finally中不能有return语句,编译都无法通过,提示:控制不能离开finally子句主体


C# 如何获取错误所在行数


三种思路,
一种是利用error.StackTrace,
第二种是try-catch找到错误行数,
第三种是: System.Diagnostics.Debug.WriteLine() + DebugView工具

一、error.StackTrace代码

</>code

  1. ex.StackTrace.Substring(ex.StackTrace.IndexOf("行号"), ex.StackTrace.Length - ex.StackTrace.IndexOf("行号"))

二、try-catch代码

</>code

  1. try
  2. {
  3.    
  4.    //代码
  5. }catch(Exception ex)
  6. {
  7.     MessageBox.Show(ex.StackTrace);
  8. }

vb.net代码:

</>code

  1. Try 
  2.     '代码
  3. Catch ex As Exception
  4.     MsgBox(ex.StackTrace)
  5. End Try

三. System.Diagnostics.Debug.WriteLine() + DebugView工具


1.引用

 using System.Diagnostics;

 
2.显示在DebugView的信息
Debug.WriteLine(DateTime.Now.ToString("HH-mm-ss")+" "+DateTime.Now.Millisecond.ToString() + " cti_message", "my");
 
3.在Dbgview.exe 过滤其它信息
Edit -> Filter/Hightlight... -> include: 中输入 *my 
点击OK后,便可用DebugView调试C#程序了。


MSDN StackTrace示例

下面的代码示例引发一个 Exception,然后捕捉该异常,并使用 StackTrace 属性显示堆栈跟踪。

</>code

  1. // Example for the Exception.HelpLink, Exception.Source,
  2. // Exception.StackTrace, and Exception.TargetSite properties.
  3. using System;
  4. namespace NDP_UE_CS
  5. {
  6. // Derive an exception; the constructor sets the HelpLink and
  7. // Source properties.
  8. class LogTableOverflowException : Exception
  9. {
  10. const string overflowMessage = "The log table has overflowed.";
  11. public LogTableOverflowException(
  12. string auxMessage, Exception inner ) :
  13. base( String.Format( "{0} - {1}",
  14.                    overflowMessage, auxMessage ), inner )
  15. {
  16. this.HelpLink = "http://msdn.microsoft.com";
  17. this.Source = "Exception_Class_Samples";
  18. }
  19. }
  20. class LogTable
  21. {
  22. public LogTable( int numElements )
  23. {
  24. logArea = new string[ numElements ];
  25. elemInUse = 0;
  26. }
  27. protected string[ ] logArea;
  28. protected int       elemInUse;
  29. // The AddRecord method throws a derived exception if
  30. // the array bounds exception is caught.
  31. public    int       AddRecord( string newRecord )
  32. {
  33. try
  34. {
  35. logArea[ elemInUse ] = newRecord;
  36. return elemInUse++;
  37. }
  38. catch( Exception e )
  39. {
  40. throw new LogTableOverflowException(
  41. String.Format( "Record \"{0}\" was not logged.",
  42. newRecord ), e );
  43. }
  44. }
  45. }
  46. class OverflowDemo
  47. {
  48. // Create a log table and force an overflow.
  49. public static void Main()
  50. {
  51. LogTable log = new LogTable( 4 );
  52. Console.WriteLine(
  53. "This example of \n   Exception.Message, \n" +
  54. "   Exception.HelpLink, \n   Exception.Source, \n" +
  55. "   Exception.StackTrace, and \n   Exception." +
  56. "TargetSite \ngenerates the following output." );
  57. try
  58. {
  59. for( int count = 1; ; count++ )
  60. {
  61. log.AddRecord(
  62. String.Format(
  63. "Log record number {0}", count ) );
  64. }
  65. }
  66. catch( Exception ex )
  67. {
  68. Console.WriteLine( "\nMessage ---\n{0}", ex.Message );
  69. Console.WriteLine(
  70. "\nHelpLink ---\n{0}", ex.HelpLink );
  71. Console.WriteLine( "\nSource ---\n{0}", ex.Source );
  72. Console.WriteLine(
  73. "\nStackTrace ---\n{0}", ex.StackTrace );
  74. Console.WriteLine(
  75. "\nTargetSite ---\n{0}", ex.TargetSite );
  76. }
  77. }
  78. }
  79. }
  80. /*
  81. This example of
  82.   Exception.Message,
  83.   Exception.HelpLink,
  84.   Exception.Source,
  85.   Exception.StackTrace, and
  86.   Exception.TargetSite
  87. generates the following output.
  88. Message ---
  89. The log table has overflowed. - Record "Log record number 5" was not logged.
  90. HelpLink ---
  91. http://msdn.microsoft.com
  92. Source ---
  93. Exception_Class_Samples
  94. StackTrace ---
  95.   at NDP_UE_CS.LogTable.AddRecord(String newRecord)
  96.   at NDP_UE_CS.OverflowDemo.Main()
  97. TargetSite ---
  98. Int32 AddRecord(System.String)
  99. */



如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛

发表评论 (1733人查看0条评论)
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
昵称:
最新评论
------分隔线----------------------------

快速入口

· 365软件
· 杰创官网
· 建站工具
· 网站大全

其它栏目

· 建站教程
· 365学习

业务咨询

· 技术支持
· 服务时间:9:00-18:00
365建站网二维码

Powered by 365建站网 RSS地图 HTML地图

copyright © 2013-2024 版权所有 鄂ICP备17013400号