C # And. NET3.5 advanced programming (version 4th) Note 7

Source: Internet
Author: User

Chapter 7 structured exception handling

This chapter describes how to use structured exception handling to handle runtime exceptions in C # code. This article not only describes the keyword for exception handling, but also understands the differences between application-level and system-level exceptions and the basic classes of exceptions.

7.1. NET Exception Handling

. NET structured exception handling is an appropriate solutionRuntimeAbnormal technology. It provides a standard technique for sending and capturing runtime errors, which is structured exception handling (SEH ). The advantage is that developers are provided with a unified way to handle exceptions in the. NET field using the same language. In addition, it provides easy-to-understand problem description and help information.

. NET Exception HandlingFour Elements:

(1) A class type that indicates Exception details: for example, the base class System. Exception class orCustom class.

(2) One callerCauseMember of an exception class instance: This is where throw statements are generated. How do I know which members of the exception class may cause exceptions? You can query a method through the SDK documentation, which lists possible exceptions caused by this method. In addition, in. in the. NET platform, by hovering over a method, you can also prompt the Member for possible exceptions. As shown in, it indicates that three exceptions may be thrown when the ReadLind method is executed.

(3) a piece of code block for the caller to call abnormal members: Common Code that may cause errors, such as int a = int. parse (console. writeline ());

(4) Processing (orCapture) Code block to be exception: try/catch Block.

All user-defined and system-defined exceptions are ultimately inherited from the system. exception base class (of course, It inherits from the object ). It has multiple constructor and override methods and attributes. Its attributes include TatgetSite, StackTrace, HelpLink, and Data, which are useful when obtaining exception details!

7.2 exception

When a method in a class is executed, an error message (such as messagebox. show ("error!") is displayed when an error is identified !")), Of course, you can also use the throw keyword of C # to return an error object to a caller, for example:

Public void accelerate (int data) {// some normal code execution if (data> 100) // throw an exception
Throw new exception ("error !");
// Of course, you can also instantiate an exception, set some attributes, and then throw}

Note: if an exception is thrown, it is always up to us to decide the problem and when to cause the exception. The exception should be in only oneMore fatal conditionsWhen this condition is met, it is a design issue that should be addressed to determine the conditions under which exceptions will be thrown.

7.3 capture exceptions

Because an exception has been thrown above, when the caller calls this method, if the possible exception is handled or caught, try/catch Block should be used. Once the exception object is caught, release detailed information about the problem by calling the caught exception class members.

Try () {accelerate (10);} catch (exception e) // catch an exception that may be thrown by the accelerate method {console. writeline (e. message);} finally {}

Here, try is part of the declaration that may cause exceptions during execution. For example, the accelerate () method should be called here.

If no exception is triggered in try, the catch block is skipped directly. If the code in try triggers an exception, the remaining code in try will not be executed, and the program immediately enters the corresponding catch block. There may be multiple catch blocks to capture different types of exceptions, whether a catch block can be entered depends on whether the caught exception is consistent with the exception class declared after the catch (or its parent class ). Remember, you can only enter the first matched catch Block. Therefore, you should put the specific exception in front and put the common or wider range in the back! If an exception is caught but no catch Block matches, the program will be interrupted during running and an error box will pop up, which will greatly prevent end users from using our program. As shown in:

 

Of course, when debugging, the pop-up box allows us to determine the details of the Error. Click View Details to view all information about the exception object, as shown in:

 

In addition, general catch statements are also supported. It does not display exceptions that are thrown by specified members, that is, exceptions e are not needed. However, this is not a recommended method, because exceptions cannot be output, only some common code for exception handling is executed after the try captures exceptions.

Raise an exception again

You can trigger an exception again to the previous caller in catch. You only need to use the throw keyword in this block. It passes an exception by calling the logical chain, which can only be used in catch blocks.ProcessingComing soonSome errorsUseful:

Try {} catch (CarIsDeadexception e) {// execute some operations to handle this error and pass an exception
throw; } 

Of course, the CarIsDeadexception object is not explicitly re-thrown here, but the throw keyword without parameters is used, so that the context of the original object can be retained.

Note: throws without parameters can only be caught. It throws the exceptions caught by the current catch Block and should be outside this try/catch, try/catch to catch this exception. Otherwise, it will be captured by CLR. This is not a recommended method.

Internal exception

That is to say, we can trigger another exception when handling other exceptions. For example, if you need to read the file when handling an exception in catch, the exception that does not exist in the file may occur, therefore, it is conceivable to catch this exception in this catch. The best habit (recommended, but not mandatory) is to mark this new exception object as the first exception type.SameInternal exception in the new object ". The only way to declare an internal exception is to use it as a constructor parameter. The following example shows an extension:

Try {} catch (CarIsDeadexception e) {try {} catch (exception e2) {// exception Handling
Throw new CarIsDeadexception (e. message, e2); // the exception that records new exceptions and the information about the first exception }}

Note that this new internal exception is not captured by the outer try/catch Block, but is to be captured by the caller using try/catch, at this time, the caught exception should be of the internal exception type (as recommended above, it should be consistent with the external exception type), so that the detailed information of the caught exception can be accessed through InnerException. Otherwise, it will be sent to CLR for capture, which will result in an error prompt box.

A finally block may be defined next to a try/catch Block. It is not necessary to ensure that a set of code statements, no matter whether the block is abnormal or not.AlwaysCan be executed!

Extended topic, about try/catch/finally:

  • Once an exception occurs in a try statement, the remaining code segment of try is no longer executed, but the catch Block is switched. If the catch Block is not captured, the upstream caller throws an exception.
  • If the try/catch/finally structure exists, the code will follow try-finally (no exception) or try-catch-finally (catch caught exception) or only execute try (remember to setNo finally execution, This is because catch does not capture the specified type exception, and continues to throw an exception to the upper layer.
  • If there is a try/finally structure, that is, there is no catch block, the code will follow try-finally (no exception) or only execute try (similar to the above explanation).
  • If return exists in try or catch, one of them must be executed.Return to executeThe code in finally cannot be changed in finally.
  • Return cannot exist in finally.

7.4 exception

. NET exceptions include system-level exceptions and application-level exceptions.

System Level exception :.NET base class library defines many derived from System. exception class. To be precise.. NET platform exceptions should be system exceptions, which are considered to be unrecoverable fatal errors. System exceptions are directly derived from the base class of System. SystemException, which is derived from System. Exception. When an exception class is derived from System. SystemException, we can determine that the entity causing the exception is the. NET Runtime Library rather than the application code library being executed. That's all. In short, system-level exceptions are defined exceptions in various types of the. NET platform (CLR), rather than those written by users.

Application-level exceptions:Custom exceptions should be derived from System. ApplicationException. In fact, the only purpose of an application-level exception is to identify the source of the error. It can be determined that the exception is caused by the code library of the application being executed (throw), rather than throw caused by the CLR base class library or. NET runtime engine.

In fact, neither of the above two types of exceptions is defined by any other member outside the System. Exception constructor, just to identify the type of exceptions.

Of course, you can always raise an instance of System. Exception to indicate a running error, but sometimes constructing a strong type Exception means that the unique details of the current problem are better! The principle is when to build a custom exception: you only need to create a custom exception when the error class is closely related to the error. For example, a custom file class causes many file-related errors.

We recommend that you inherit from System. ApplicationException for custom exceptions you want to build. This is a best practice. Of course, it will not cause errors if you inherit from System. Exception! As a rule, we recommend that you declare the custom exception class as public because the default type is internal, but because the exception classes are usually passed across assembly boundaries, therefore, the public type is better.

Then, rewrite the attributes and methods of the parent class.

For a strictly standardized custom exception class, you must ensure that the class complies with the. NET Exception Handling best practices:

  • Inherited from Exception/ApplicationException class;
  • With the [System. Seralizable] feature mark;
  • Define a default constructor;
  • Defines a constructor that sets the inherited message attributes;
  • Define a constructor for handling "Internal exceptions"
  • Define a constructor for processing type serialization.

Such a specification is better than. the. NET platform provides a code snippet template that automatically generates exception classes that follow the above best practices. Right-click the desired part and choose insert code snippet-visual c #-exception!

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.