Structured exception handling (1)

Source: Internet
Author: User

I. Errors, bugs, and exceptions

In. Net terminology, "exceptions" are interpreted as bugs, user input errors, and runtime errors.

Ii. Functions of. Net Exception Handling

Ideally, we want to include the incorrect name, message, and other useful information into a clear package,This is exactly what structured exception processing does.

Advantages of the structured exception handling solution:

1. Developers now have a unified approach that is common to various languages in the. NET field to handle errors.

2. the syntax used to cause a core capture exception is consistent across different Assembly sets or computers.

3. We can not identify the problem by receiving numeric constants with fuzzy meanings, but by exception,It contains easy-to-understand problem descriptions and detailed snapshots of the call stack when an exception is triggered for the first time. In addition, we can provide end users with a response help link to direct them to a URL that contains detailed error information and programmer-defined data.

Iii. Four Elements of. Net Exception Handling

For structured exception handling programming, four correlated entities are used:

1. A class type that indicates exception details;

2. A member that throws an exception class instance to the caller;

3. A code block for the caller to call abnormal code;

4. Capture the code block to be abnormal by the caller.

C # the programming language provides four keywords that allow us to raise and handle exceptions: Try, catch, throw, and finally.Indicates that the type of the problem is a class inherited from system. Exception.

Iv. system. Exception base class

Core member of the system. Exception type

System. Exception attributes Function
Data idictionary Type Read-Only This property returns a set of key/value pairs (representing an object that implements the idictionary Interface), providing more programmer-defined information about exceptions. This set is empty by default.
Helplink string type This property returns a URL pointing to a Help file or website containing detailed error Information Descriptions
Innerexception exception Type Read-Only This attribute is read-only and can be used to obtain information about the previous exception that causes the current exception. The previous exception is recorded as the constructor with the current exception passed in as a parameter.
The message string type is read-only. It is assigned a value through the constructor. This attribute is read-only and returns the text description of the specified error. The error message is a constructor parameter.
Source string type read-only Returns the name of the assembly or object that causes an exception.
Stacktrace string type read-only This attribute is read-only and contains a string that identifies the sequence for triggering an abnormal call.This attribute is useful when debugging or when you want to dump an error to an external error log.
Targetsite methodbase Type Read-Only This attribute is read-only and returns a methodbase object, which describes many details about the methods that cause exceptions.

 

 

 

 

 

 

V. A simple example

Define a car class. If a user accelerates a car object beyond the predefined maximum speed, the car engine will explode, making the car unusable.

If the user tries to accelerate the car after the car breaks down, it will cause an exception. Here we will create and set a new system. exception class instance, and assign values to the read-only attribute message through the class constructor.If an exception object is returned to the caller, you can use the throw keyword of C.

1. Common exceptions

1 public class car 2 {3 Public Car () {} 4 Public Car (string name, int speed) 5 {6 currentspeed = speed; 7 petname = Name; 8} 9 // indicates the maximum speed of 10 private const int maxspeed = 100; 11 // indicates whether the car can still manipulate 12 private bool casisdead; 13 14 public int currentspeed {Get; set ;} 15 Public String petname {Get; set;} 16 17 Public void accelerate (INT delta) 18 {19 if (casisdead) 20 {21 console. writeline ("{0} is out of order... ", Petname); 22} 23 else24 {25 currentspeed + = delta; 26 if (currentspeed> = maxspeed) 27 {28 casisdead = true; 29 currentspeed = 0; 30 31 // use the throw keyword to raise an exception 32 throw new exception (string. format ("{0} has overheated! ", Petname); 33} 34 else35 {36 console. writeline (" => currentspeed = {0} ", currentspeed); 37} 38} 39} 40}

2. Capture exceptions

 1 static void Main(string[] args) 2 { 3         Car myCar = new Car("Zippy", 20); 4  5         try 6         { 7               for (int i = 0; i < 10; i++) 8               { 9                     myCar.Accelerate(10);10               }11          }12          catch (Exception e)13          {14                 Console.WriteLine("Method: {0}", e.TargetSite);15                 Console.WriteLine("Message: {0}", e.Message);16                 Console.WriteLine("Source: {0}", e.Source);17          }18 }

Result:
=> Currentspeed = 30
=> Currentspeed = 40
=> Currentspeed = 50
=> Currentspeed = 60
=> Currentspeed = 70
=> Currentspeed = 80
=> Currentspeed = 90
Method: void accelerate (int32)
Message: Zippy has overheated!
Source: leleapplication3

Note:

1. When calling a method that may cause exceptions, use try/catch blocks. Once an exception object is captured, the exception object member can be called to release detailed information about the problem.

2. Part of the statements that may cause exceptions during the execution of try blocks. If an exception is detected, the program executes a flow into the Catch Block in the response. On the other hand, if the Code contained in try does not trigger an exception, the catch code block in the response will be skipped directly, indicating that everything is normal.

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.