[C #] C # knowledge Review,

Source: Internet
Author: User

[C #] C # knowledge Review,
Do you really understand exceptions?

Directory

  • Exception description
  • Exception features
  • Usage exception
  • Try-catch-finally for Exception Handling
    • Catch blocks with exceptions
    • Release Finally blocks of resources

 

I. exception description

When writing a program, we accidentally (or technically insufficient), which leads to exceptions (or exceptions) during the program running. For this problem, C # has a special exception handling program. Keyword involved in exception handling:try,catchAndfinallyTo handle failures. CLR,. NET class libraries, other third-party libraries, or program code you write may all encounter exceptions. Of course, you can also use throw to create exceptions explicitly.

When an exception occurs in your code, the program will find and execute the First MatchingcatchBlock. If the exception handler does not find the appropriate (you wrote) in any position in the call stackcatchThe process is automatically terminated and an error message is displayed to the user.

Here I have written an exception that will occur if it is divided by 0 (an explicit DivideByZeroException is thrown) and an example of this exception is caught:

1 /// <summary> 2 /// Division 3 /// </summary> 4 /// <param name = "x"> </param> 5 /// <param name = "y"> </param> 6 // <returns> </returns> 7 static double Division (double x, double y) 8 {9 if (y = 0) 10 {11 throw new DivideByZeroException (); 12} 13 14 return x/y; 15} 16 17 static void Main (string [] args) 18 {19 // define two variables x, y20 double x = 250, y = 0; 21 22 try23 {24 var result = Division (x, y); 25 Console. writeLine ($ "result: {result}"); 26} 27 catch (DivideByZeroException e) 28 {29 30 Console. writeLine (e); 31} 32 33 Console. read (); 34}

UsetryBlock enclose code that you think may cause exceptions.

  • OncetryWhen an exception occurs in the block, the control flow will find the catch Block associated with it in order. If no catch block is found, it will cause the final Exception to the handler in the base class Exception (if you have caught it ).

  • If an exception occurs but there is no corresponding Exception Processing Program, the program will stop running and throw the corresponding error message.

  • IncatchDefined exception variables can be used to obtain information about the corresponding exception type. For example, the status and error description of the Call Stack. For details, refer to the Excetion attribute.

  • throwKeyword can explicitly cause an exception.

  • Execute the command even if an exception occurs.finallyBlock. In general, we will usefinallyBlock to release resources. For example, disable the xx stream.

 

Iii. How to Use exceptions

Errors that occur during program running will be continuously transmitted in the program. This mechanism is called "exception ". An exception is usually caused by the error code and caught by the code that can correct the error. Exceptions can also be caused by. net clr or code in the program. Once an exception is thrown, the exception will be continuously propagated in the call stack until it finds the matchingcatchStatement. Exceptions without catch are handled by the default exception handler provided by the system, which is a dialog box that suddenly causes debugging interruption and displays exception information.

All exceptions are derived from exceptions. The types of these exceptions include the attributes that describe the exceptions in detail. Here I will customize a new exception class. In fact, I can also customize the attribute of the configuration exception (this is optional). Then I usethrowThis object (that is, an exception) is thrown when the keyword is displayed ).

1 /// <summary> 2 // define a new Exception 3 /// </summary> 4 class MyException: Exception 5 {6 public MyException (string msg) {} 7} 8 9 // <summary> 10 // throw the newly defined exception 11 /// </summary> 12 static void ThrowMyExcetion () 13 {14 throw new MyException ("Sorry, this is test! "); 15}

 

When an exception is thrown, the program checks the current statement to determine whether it is included intryBlock. If yes, it will checktryAll associated BlockscatchBlock to determine whether they can catch the exception. The catch Block usually specifies the exception type.catchIf the block type is the same (or matches) as the exception or its base classcatchBlocks can be captured and processed.

1 static void Main (string [] args) 2 {3 try 4 {5 ThrowMyExcetion (); // directly call Method 6} 7 catch (MyException e) 8 {9 Console. writeLine (e); 10} 11 12 Console. read (); 13}

1 static void Main (string [] args) 2 {3 StreamWriter sw = null; 4 5 try 6 {7 sw = new StreamWriter (@ "C: \ book \ story .txt "); 8 sw. write ("You are 250. "); 9} 10 catch (FileNotFoundException e) 11 {12 // place the exception in the first 13 Console. writeLine (e); 14} 15 catch (IOException e) 16 {17 // do not place it in the relative position 18 Console. writeLine (e); 19} 20 catch (Exception e) 21 {22 Console. writeLine (e); 23} 24 finally25 {26 if (sw! = Null) 27 {28 sw. Close (); 29} 30} 31 32 Console. Read (); 33}

 

RuncatchThe CLR checksfinallyBlock.finallyBlocks enable programmers to clear abortedtryBlocks may be left in any fuzzy state, or any external resources (instance handle, db connection, or IO stream) are released without waiting for the garbage collector in the CLR to terminate these objects. For example:

1 static void Main (string [] args) 2 {3 FileStream fs = null; 4 FileInfo fi = new FileInfo (@ "story .txt "); 5 6 try 7 {8 fs = fi. openWrite (); 9 fs. writeByte (0); 10} 11 finally12 {13 // remember, if you forget to close, IO exceptions will occur! 14 // if (fs! = Null) 15 // {16 // fs. close (); 17 //} 18} 19 20 try21 {22 fs = fi. openWrite (); 23 fs. writeByte (1); 24 Console. writeLine ("OK! "); 25} 26 catch (IOException e) 27 {28 Console. WriteLine (" Fail! "); 29} 30 31 Console. Read (); 32}

1 static void Main (string [] args) 2 {3 try 4 {5 // code to be executed 6} 7 catch (Exception e) 8 {9 // here we can get the caught exception 10 // you need to know how to handle this exception 11} 12}

 

(2) try-finally:

1 try2 {3 // code to be executed 4} 5 finally6 {7 // code executed after try block 8}

 

(3) try-catch-finally:

1 try 2 {3 // code to be executed 4} 5 catch (Exception e) 6 {7 // handle exceptions here 8} 9 finally10 {11 // code 12 executed after try block (or catch block}

[Note] does not containcatchOrfinallyBlocktryBlock will cause a compiler error.

 

4.1 Catch blocks with exceptions

  catchBlock can specify the exception type to capture, also known as "exception filter ". All Exception types are derived from Exception. Generally, the System. Exception class of all exceptions is not specified as the "Exception filter" to catch, unless you know how to handle exceptionstryBlock, orcatchThe block contains the throw statement.

MultiplecatchBlocks can be connected together (different exception filters are required ). MultiplecatchThe execution sequence of blocks is: from the top to the bottom of the Code. However, for every exception thrown during runtime, the program will only execute onecatchData Block. The first matching of the specified exception type or its base classcatchBlock to be executed. In general, we need to set the exception class of the most special (most specific or derivative) SectioncatchThe block is placed at the beginning of all catch blocks, and the catch Block of their base class Excetion is placed at the end (of course, you can also leave it empty ).

When the following conditions are true, you should select catch exception:

  • Understand the cause of the exception and enable selective recovery. For example, when capturing FileNotFoundException, You can prompt the user to "file not found" and "enter a new file name.

  • You can also create a more specific or representative exception and choose to cause the exception.

1 double GetNum (double [] nums, int index) 2 {3 try 4 {5 return nums [index]; 6} 7 catch (IndexOutOfRangeException e) 8 {9 throw new ArgumentOutOfRangeException ("Sorry, the index you want has exceeded the limit! "); 10} 11}

  

When we want to throw an exception, we usually choose to handle some exceptions. In the following example,catchAdd error logs before throw again.

1 try 2 {3 // try to access system resources 4} 5 catch (Exception e) 6 {7 // pseudocode: Record Error log 8 log. error (e); 9 10 // re-throw Error 11 throw; 12}

 

4.2 release Finally blocks of resources

AvailablefinallyBlock release (cleanup) intryBlock. If yesfinallyBlock, It will be executed at the end, that is, intryBlock and any matchcatchBlock. Whether an exception is thrown or whether the exception type matchescatchBlock,finallyIt will always run.

AvailablefinallyBlock releases resources (such as IO streams, DB connections, and graphical handles), instead of waiting for the garbage collector in the runtime to recycle the object Resources. In fact, we recommend that you use the using statement.

In the following examplefinallyBlock close intryBlock. Note: You should check the file handle status before closing the file. IftryThe file cannot be opened, the file handle value is stillnull, Then,finallyBlock will not try to close it. Or, iftryThe file is successfully openedfinallyBlock.

1 static void Main (string [] args) 2 {3 FileStream fs = null; 4 FileInfo fi = new System. IO. fileInfo ("C :\\ story .txt"); 5 6 try 7 {8 fs = fi. openWrite (); 9 fs. writeByte (0); 10} 11 finally12 {13 // remember to judge null. Otherwise, other exceptions may be triggered. 14 if (fs! = Null) 15 {16 fs. Close (); 17} 18} 19 20}

 

C # basic Review Series

C # knowledge Review-serialization

C # knowledge Review-Expression Tree Expression Trees

C # knowledge Review-feature Attribute and AssemblyInfo. cs-understanding common feature attributes

C # knowledge Review-delegated delegate and C # knowledge Review-delegated delegate (continued)

C # knowledge Review-Introduction to events and C # knowledge Review-Event Events

There is no unspeakable secret between the string, the String, the big S, and the small S

 

 

[Blogger] Anti-Bot

[Source] http://www.cnblogs.com/liqingwen/p/6206251.html

[Reference] Microsoft official documentation

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.