[Reading Notes] C # errors and exceptions in chapter 1 of Advanced Programming,

Source: Internet
Author: User
Tags finally block

[Reading Notes] C # errors and exceptions in chapter 1 of Advanced Programming,

(1) Introduction

Errors are not always caused by the people who write the application. Sometimes the application may encounter errors because the end user of the application triggers or runs the code environment. C # provides an exception processing mechanism to handle errors.

 

 

(2) Exceptions

In C #, an exception object is created (or thrown) when a special exception error condition occurs. Generally, the exception does not have a specific namespace. The exception class should be placed in the namespace of the generated exception class.

 

 

(3) Capture exceptions

. NET Framework provides a large number of predefined basic class exception objects. In order to handle possible errors in C # code, the related parts of the program are generally divided into three different types of code blocks.

The Code contained in the try block is the normal operation part of the program, but this part of the program may encounter some serious errors.

The Code contained in the catch Block handles various errors, which are encountered when the code in the try block is executed.

The finally block contains code to clear resources or execute other operations that are usually performed at the end of the try block or catch block (whether or not an exception is thrown, The finally block will be executed ).

Try {// code} catch (Exception) {// multiple catch can be set to catch different exceptions (capture order from top to bottom)} finally {// can be omitted}

 

1. implement multiple catch Blocks

Try {// code} catch (IOException) {// multiple catch can be set to catch different exceptions (capture order from top to bottom)} catch (Exception) {// you can set multiple catch methods to catch different exceptions (from top to bottom)} finally {// can be omitted}

The catch blocks first written are used to handle very special errors, followed by general blocks. They can handle any errors and we have not compiled specific error handling programs for them. The order of catch blocks is very important. If you write these two blocks in the opposite order, the code will not be compiled, because the second catch block will not be executed.

 

2. System. Exception attributes

Var exception = new Exception (); exception. data ["ErrorDate"] = DateTime. now; // The first method for adding additional information about exceptions: exception. data. add ("AdditionalInfo", "exception additional information"); // method 2 exception for adding exception additional information. helpLink = "excption.txt"; // exception in the Help File exception. source = "test abnormal application"; // Application name or object name that causes the exception

The above is the writeable attribute of Exception, in addition to the readable attribute. InnerException is thrown in the catch block, which contains the exception object that sends the code to the catch Block; the Message text that describes the error situation; the detailed information of method calls on the StackTrace stack; targetSite describes how to throw an exception. NET reflection object.

 

3. nested try Blocks

1 try 2 {3 // outer code A 4 // (exception thrown here, handled by outer exception) 5 try 6 {7 // inner code 8 // (exception thrown here, if the inner layer exception can be handled, otherwise the outer layer exception will be handled.) 9 // Note: if the inner layer cannot handle the exception, after the finally internal method is executed, 10 // look for outer matching Exception Handling. At this time, outer code B does not run 11} 12 catch (Exception) // internal Exception Handling 13 {14 // you can set multiple catch to catch different exceptions (capture order from top to bottom) 15 // (an exception is thrown here, which is handled by an outer exception) 16} 17 finally18 {19 // 20 may be omitted // (exception thrown here, handled by outer exception) 21} 22 // outer code B23 // (exception thrown here, exception Handling by outer layer) 24} 25 catch (Exception) // Exception handling by outer layer 26 {27 // you can set multiple catch to catch different exceptions (capture order from top to bottom) 28} 29 finally30 {31 // 32 may be omitted}

 

 

(4) user-defined exceptions

Class Program {static void Main (string [] args) {try {// 2. throw a custom exception throw new MyException ("custom exception information ");} catch (MyException ex) // 3. Capture custom exceptions {Console. writeLine (ex. message );}}}
// 1. custom Exception class public class MyException: Exception {// pass Exception information to the base class constructor public MyException (string message): base (message) {} public MyException (string message, Exception innerException): base (message, innerException ){}}

 

 

(5) Caller information

When an error is processed, obtain the information about the location where the error occurred. C #5.0 provides a new feature that can be obtained using features and optional parameters (defined in System. Runtime. CompilerServices ).

 1 static void Main(string[] args) 2 { 3     var p = new Program(); 4     p.Log(); 5     p.SomeProperty = 33; 6     Action a = () => p.Log(); 7     a(); 8 } 9 private int someProperty;10 public int SomeProperty11 {12     get { return someProperty; }13     set {14         this.Log();15         someProperty = value;16     }17 }18 public void Log([CallerLineNumber] int line = -1, [CallerFilePath]string path = null, [CallerMemberName]19 string name = null)20 {21     Console.WriteLine((line < 0) ? "No Line" : "Line " + line);22     Console.WriteLine((path == null) ? "No file path" : "Line " + path);23     Console.WriteLine((name == null) ? "No member name" : "Line " + name);24     Console.WriteLine();25 }

 

 

Run the above Code and the result is as follows:

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.