. NET Framework Exception Handling

Source: Internet
Author: User
Tags processing instruction
Document directory
  • Note:
  • How does CLR capture and handle exceptions?
. NET Framework exception (msdn)

An exception is any error or unexpected behavior encountered by the program being executed. Any of the following situations can cause exceptions: your code or called code (such as the shared library) has errors and the operating system resources are unavailable, exceptions occurred when running the common language (for example, Code cannot be verified. Applications can recover from some of these situations, but cannot recover from other situations. Although it can be recovered from most application exceptions, it cannot be recovered from most runtime exceptions.

In. NET Framework, an exception is an object inherited from the system. exception class. An exception is thrown from the problematic code area and then passed up the stack until the application processes it or the program ends.

Exception and traditional error handling methods

Traditionally, the language error processing model relies on the unique method of detecting errors and finding error handling programs, or on the error processing mechanism provided by the operating system. Exception Handling During running has the following features:

  • When handling an exception, you do not need to consider generating the exception language or the language that handles the exception.

  • Exception Handling does not require any specific language syntax, but allows each language to define its own syntax.

  • Cross-process or even cross-computer boundary exceptions are allowed.

Compared with other error notification methods (such as return code), exceptions have several advantages. There are no errors that are not noticed. Invalid values will not continue to be transmitted in the system. You do not have to check the return code. You can easily add Exception Handling Code to increase program reliability. Finally, exception handling during running is faster than Windows-based c ++ error handling.

Because the execution thread routinely traverses hosted and unmanaged code blocks, exceptions can be caught or thrown in managed or unmanaged code blocks during runtime. Unmanaged code can contain both C ++-style seh exceptions and com-based hresult.

How to manage exceptions during running

Use an exception handling Model Based on exception objects and protected code blocks during runtime. When an exception occurs, create an exception object to indicate the exception.

Create an exception information table for each executable file during runtime. In the exception information table, each method of the executable file has an array of associated exception handling information (which can be empty ). Each item in the array describes a protected code block, any exception filter associated with the code, and any exception handler (catch Statement ). This exception table is very effective and will not cause performance loss in terms of CPU time or memory usage if no exception occurs. Use resources only when exceptions occur.

The exception information table provides four types of exception handlers for protected blocks:

  • The finally processing program executes every time a block exits, regardless of whether the exit is caused by a normal control flow or an unhandled exception.

  • Error handler, which must be executed when an exception occurs, but not when the normal control flow is completed.

  • Type filtering handler that processes any exceptions of a specified class or any derived class of this class.

  • The user-filtered handler that runs the code specified by the user to determine whether the exception should be handled by the associated handler or transmitted to the next protected block.

Each language implements these exception handlers according to its own specifications. For example, Visual Basic provides access to user-filtered handlers by comparing variables in catch statements (using the when keyword); C # does not implement user-filtered handlers.

When an exception occurs, the running process consists of the following two steps:

  1. During runtime, search for the first protected block that performs the following operations in the array:

    • Protects the region that contains the currently executed commands.

    • Contains an exception handler or a filter containing the exception handling.

  2. If a match exists, an exception object is created during the runtime to describe the exception. Then, execute all finally statements or error statements between the statement with the exception and the statement with the exception. Note that the order of exception handling programs is very important; the exception handling program in the top is the first to calculate. Note that the exception handler can access the local variables and local memory of the exception capture routine, but any median value will be lost when an exception is thrown.

    If no matching item exists in the current method, search for each caller of the current method at runtime and keep searching up the stack. If no caller has a match, the debugger is allowed to access the exception during running. If the debugger cannot be attached to this exception, the appdomain. unhandledexception event is triggered during the runtime. If there is no listener for this event, the runtime dumps the stack trace and ends the application.


    Note: How does CLR capture and handle exceptions?



    For any class in A. NET application, the methods that are inclusive include an exception handling table. If this method does not use try... Catch... Finally, the table is empty (that is, the Il command generated by this method does not include any exception handling clauses ).


    When. when the net application is running, if an exception is thrown by a method being executed, the CLR first pushes the exception object to the computing stack, then scan the exception handling table included in this method to find the handler. The processing process can be described as follows:


    The CLR obtains the Il command address that causes the exception, scans the exception handling table from top to bottom, and extracts ". the try keyword is followed by the start and end addresses of the block to determine whether the abnormal il command address is "included" in the address range. If yes, check whether the exception type followed by the keyword "catch" is consistent with the type (or compatible) of the thrown exception object. If this condition is met, CLR extracts the two IL addresses after handler,PreparationRun the Il commands specified by the two addresses (this is the exception handling code in the catch command block ).


    If no appropriate catch clause is found in the exception handling table for this method, CLR will call the stack based on the method associated with the thread that causes the exception, find the exception handling table that the caller of this method can tolerate.


    This process continues until you find a handler that can handle this exception.


    Assume that CLR is a "Link" of the entire method call chain (that is, an "ancestor" method that calls this method) the contained Exception Handling table finds the catch exception handling clause that can handle this exception. It completes the "Preparation" of the exception handling instruction code block defined by this clause ".


    The process of "scanning and searching for matched catch clauses" is the first round of CLR exception handling process.


    After an appropriate exception handling code is found, CLR "returns to the original location" and scans the exception handling table that is included in the exception handling method. This time, CLR no longer focuses on catch clauses, instead, it is a finally clause. If a suitable finally clause is found (you only need to determine whether the Il command address that causes the exception "falls within the range of the Il command address monitored by a finally clause ), CLR executes the processing instruction specified by the finally clause (that is, the Il instruction within the range specified by the handler part ).


    The process of "scanning and searching for matched finally clauses" is the second round of CLR exception handling process.


    The second round of scanning started with the method that triggered the exception, and ended with the method that included the method that triggered the exception at the top, for example, if you have a nested deep function call statement and an exception is thrown in the bottommost called function, and you use try again in the top-level Main () function... catch... if finally is surrounded by this function call statement, the 2nd round of scanning will "go" to the top-level Main () method Exception Handling table, it will not stop in the middle of finding the appropriate catch clause ".


    After all the "lower-layer" Finally clauses are executed, the exception handling code block specified by the catch clause starts execution. Then, the catch clause"Same layer"The exception handling code block specified by the finally Clause of is executed.


    However, this is not complete yet. Now it is our turn to allow all the finally clauses in the "parent" method of the method where the catch clause is executed.


    After two rounds of scanning, CLR has completed the capture and processing of exceptions caused by. NET applications.


    A problem persists:


    What should I do if the CLR cannot find an appropriate catch exception handling clause?


    If. the net application does not define code to handle a certain type of exception at all, and this program actually triggers this type of exception at runtime (which pot does not open which pot ), in the first round of scanning, the CLR will "Roll back" to the exception handling table included in the main () method, and then "return without success ".


    The CLR performs a second round of scanning to execute all the finally clauses that should be executed.


    The end of the story is: after all finally code is executed, CLR forces to stop all threads created by this process (even if they are running normally), and an "error" dialog box is displayed in the operating system, wait for the user to respond, or end or attach a debugger to debug the process.

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.