C#中try catch finally 用法
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
- try
- {
- DataConnection.Open();
- DataCommand.ExecuteReader();
- ...
- return;
- }
- finally
- {
- DataConnection.Close();
- }
无论是否抛出异常,也无论从什么地方return返回,finally语句块总是会执行,这样你有机会调用Close来关闭数据库连接(即使未打开或打开失败,关闭操作永远是可以执行的),以便于释放已经产生的连接,释放资源。
顺便说明,return是可以放在try语句块中的。但不管在什么时机返回,在返回前,finally将会执行。
小结
</>code
- try
- {
- //执行的代码,其中可能有异常。一旦发现异常,则立即跳到catch执行。否则不会执行catch里面的内容
- }
- catch
- {
- //除非try里面执行代码发生了异常,否则这里的代码不会执行
- }
- finally
- {
- //不管什么情况都会执行,包括try catch 里面用了return ,可以理解为只要执行了try或者catch,就一定会执行 finally
- }
vb.net写法:
</>code
- Try
- Catch ex As Exception
- MsgBox(ex.Message)
- End Try
完整程序代码如下:
</>code
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace _3_16
- {
- class Program
- {
- static void ProcessString(string str)
- {
- if (str == null)
- { throw new ArgumentNullException();
- }
- }
- static void Main()
- {
- Console.WriteLine("输出结果为:");
- try
- {
- string str = null;
- ProcessString(str);
- }
- catch (ArgumentNullException e)
- {
- Console.WriteLine("{0} First exception.", e.Message);
- }
- catch (Exception e)
- {
- Console.WriteLine("{0} Second exception.", e.Message);
- }
- }
- }
- }
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
- public static string[] TestYinYong()
- {
- string[] arr = { "one", "two" };
- try
- {
- throw new Exception();
- }
- catch (Exception)
- {
- return arr;
- }
- finally
- {
- arr[1] = "three";
- }
- }
此时返回的值是:{ "one", "three" };
4.finally中不能有return语句,编译都无法通过,提示:控制不能离开finally子句主体
C# 如何获取错误所在行数
三种思路,
一种是利用error.StackTrace,
第二种是try-catch找到错误行数,
第三种是: System.Diagnostics.Debug.WriteLine() + DebugView工具
一、error.StackTrace代码
</>code
- ex.StackTrace.Substring(ex.StackTrace.IndexOf("行号"), ex.StackTrace.Length - ex.StackTrace.IndexOf("行号"))
二、try-catch代码
</>code
- try
- {
- //代码
- }catch(Exception ex)
- {
- MessageBox.Show(ex.StackTrace);
- }
vb.net代码:
</>code
- Try
- '代码
- Catch ex As Exception
- MsgBox(ex.StackTrace)
- 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
- // Example for the Exception.HelpLink, Exception.Source,
- // Exception.StackTrace, and Exception.TargetSite properties.
- using System;
- namespace NDP_UE_CS
- {
- // Derive an exception; the constructor sets the HelpLink and
- // Source properties.
- class LogTableOverflowException : Exception
- {
- const string overflowMessage = "The log table has overflowed.";
- public LogTableOverflowException(
- string auxMessage, Exception inner ) :
- base( String.Format( "{0} - {1}",
- overflowMessage, auxMessage ), inner )
- {
- this.HelpLink = "http://msdn.microsoft.com";
- this.Source = "Exception_Class_Samples";
- }
- }
- class LogTable
- {
- public LogTable( int numElements )
- {
- logArea = new string[ numElements ];
- elemInUse = 0;
- }
- protected string[ ] logArea;
- protected int elemInUse;
- // The AddRecord method throws a derived exception if
- // the array bounds exception is caught.
- public int AddRecord( string newRecord )
- {
- try
- {
- logArea[ elemInUse ] = newRecord;
- return elemInUse++;
- }
- catch( Exception e )
- {
- throw new LogTableOverflowException(
- String.Format( "Record \"{0}\" was not logged.",
- newRecord ), e );
- }
- }
- }
- class OverflowDemo
- {
- // Create a log table and force an overflow.
- public static void Main()
- {
- LogTable log = new LogTable( 4 );
- Console.WriteLine(
- "This example of \n Exception.Message, \n" +
- " Exception.HelpLink, \n Exception.Source, \n" +
- " Exception.StackTrace, and \n Exception." +
- "TargetSite \ngenerates the following output." );
- try
- {
- for( int count = 1; ; count++ )
- {
- log.AddRecord(
- String.Format(
- "Log record number {0}", count ) );
- }
- }
- catch( Exception ex )
- {
- Console.WriteLine( "\nMessage ---\n{0}", ex.Message );
- Console.WriteLine(
- "\nHelpLink ---\n{0}", ex.HelpLink );
- Console.WriteLine( "\nSource ---\n{0}", ex.Source );
- Console.WriteLine(
- "\nStackTrace ---\n{0}", ex.StackTrace );
- Console.WriteLine(
- "\nTargetSite ---\n{0}", ex.TargetSite );
- }
- }
- }
- }
- /*
- This example of
- Exception.Message,
- Exception.HelpLink,
- Exception.Source,
- Exception.StackTrace, and
- Exception.TargetSite
- generates the following output.
- Message ---
- The log table has overflowed. - Record "Log record number 5" was not logged.
- HelpLink ---
- http://msdn.microsoft.com
- Source ---
- Exception_Class_Samples
- StackTrace ---
- at NDP_UE_CS.LogTable.AddRecord(String newRecord)
- at NDP_UE_CS.OverflowDemo.Main()
- TargetSite ---
- Int32 AddRecord(System.String)
- */
如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛