How to convert a Seh-type system exception to a C ++-type exception

Source: Internet
Author: User
Tags vc runtime
Document directory
  • Why should we convert a Seh-type system exception to a C ++-type exception?
  • How can we convert a system exception of the seh type to a C ++ exception?
  • Summary
In the previous article, we discussed in detail the "mixed use of seh and C ++ exception models". In this article, the hero, a Yu, continues to deepen the topic, that is, "how to convert a Seh-type system exception to a C ++-type exception?" (In fact, this is essentially a mix of seh and C ++ exception models, that is, the C ++ exception model to capture seh system type exceptions ).

Why should we convert a Seh-type system exception to a C ++-type exception?

Before doing one thing, we 'd better find out why! How many top talents have "100,000 why" been created! Haha! Why? ? Why? Why? This is definitely a good habit for anyone. A Yu has always regarded this as a "baby ". So why should we convert a system exception of the seh type into a C ++ type? Everyone, friends, think about it and sort out their opinions and ideas. Here, ayu gives his personal understanding as follows:

• First, because we are still better at following the suggestions and advice given by msdn during programming ("try-try t and try-finally in C Programs; the C ++ program should use try-Catch "). However, in order to improve program reliability (to prevent unexpected system exceptions and cause Program-less crash), we must also require that in C ++ programs, the try-catch model can be used to capture and handle system exceptions. This has been discussed in detail in the articles in episode 3rd, that is, it can only use catch (...) Syntax to capture system exceptions of the seh type. Catch (...) Although it improves the program reliability to a certain extent, it does not provide anything to programmers (including the types of system exceptions, location, and other information about exceptions ). Therefore, we need an effective way to convert a Seh-type system exception to a C ++-type exception? This undoubtedly provides a way to not only handle system exceptions in the C ++ Exception Handling model, but also to obtain detailed information about seh system exceptions.

• A Yu has repeatedly stated that C ++ exception handling is closely related to object-oriented processing (two of them are "two good"). Therefore, if we unify the system exceptions of the seh type into the "exception Classification" of the object-oriented architecture design, it is not amazing for programmers! Beautiful! This solution improves reliability and elegance!

How can we convert a system exception of the seh type to a C ++ exception?

Although Converting System exceptions of the seh type into exceptions of the C ++ type brings many benefits to C ++ programmers, the implementation is not complicated, because the underlying system and the VC Runtime Library have already paved the way for us, that is, we can easily deal with it through the "_ set_se_translator" function in the VC Runtime Library. The description in msdn is as follows:

Handles Win32 exceptions (C structured exceptions) as C ++ typed exceptions.

TypedefVoid(* _ Se_translator_function )(UnsignedInt,Struct_ Prediction_pointers *);

_ Se_translator_function_ Set_se_translator (_ Se_translator_functionSe_trans_func);

The_ Set_se_translatorFunction provides a way to handle Win32 exceptions (C structured exceptions) as C ++ typed exceptions. To allow each c exception to be handled by a C ++CatchHandler, first define a C exception "wrapper" class that can be used, or derived from, in order to attribute a specific class type to a C exception. to use this class, install a custom C exception translator function that is called by the internal exception-handling mechanic each time a C exception is raised. within your translator function, you can throw any typed exception that can be caught by a matching C ++CatchHandler.

To specify a custom translation function, call_ Set_se_translatorWith the name of your translation function as its argument. The translator function that you write is called once for each function invocation on the stack that hasTryBlocks. There is no default translator function.

In a multithreaded environment, translator functions are maintained separately for each thread. Each new thread needs to install its own translator function. Thus, each thread is in charge of its own translation handling.

The se_trans_func function that you write must take an unsigned integer and a pointer to a Win32_ Prediction_pointersStructure as arguments. The arguments are the return values of callto the Win32 APIGetexceptioncodeAndGetexceptioninformationFunctions, respectively.

As for the specific mechanism of the _ set_se_translator function and the principle of converting the system exception to the C ++ type, we will not discuss it in detail here, but just give a general workflow: first, use the _ set_se_translator function to set a callback handler for all windows system exceptions (also related to TLS data). Therefore, when a program runs, a system exception occurs, the previously set custom callback function will accept the control of the program. Then, in the implementation of this function, we can choose different types of system exceptions (exception_pointers ), to throw a C ++ exception. Haha! Easy! I am not talking about it anymore. Let's take a look at a simple demo routine designed by Ayu! The Code is as follows:

// Filename: SEH-test.cpp

# Include <windows. h>

# Include <cstdio>

# Include <eh. h>

# Include <string>

# Include <exception>

Using namespace STD;

//////////////////////////////////////// ////////////////////////////////////////

Class seh_exception_base: public STD: exception

{

Public:

Seh_exception_base (const pexception_pointers pexp, STD: String what)

: M_exceptionrecord (* pexp-> predictionrecord ),

M_contextrecord (* pexp-> contextrecord ),

M_what (what ){};

~ Seh_exception_base () Throw (){};

Virtual const char * What () const throw ()

{

Return m_what.c_str ();

}

Virtual DWORD exception_code () const throw ()

{

Return m_exceptionrecord.exceptioncode;

}

Virtual const exception_record & get_exception_record () const throw ()

{

Return m_exceptionrecord;

}

Virtual const Context & get_context () const throw ()

{

Return m_contextrecord;

}

// Initialize the Function

Static void initialize_seh_trans_to_ce ()

{

_ Set_se_translator (trans_func );

}

// Callback function when a system exception occurs

Static void trans_func (unsigned int U, exception_pointers * pexp );

Protected:

STD: String m_what;

Prediction_record m_exceptionrecord;

Context m_contextrecord;

};

//////////////////////////////////////// ////////////////////////////////////////

// The following is the c ++ type exception after the system exception is converted

// Limited space, so only a simple design of the conversion of several common system exceptions

//////////////////////////////////////// ////////////////////////////////////////

Class seh_exception_access_violation: Public seh_exception_base

{

Public:

Seh_exception_access_violation (const pexception_pointers pexp, STD: String what)

: Seh_exception_base (pexp, what ){};

~ Seh_exception_access_violation () Throw (){};

};

//////////////////////////////////////// ////////////////////////////////////////

//////////////////////////////////////// ////////////////////////////////////////

Class seh_exception_divide_by_zero: Public seh_exception_base

{

Public:

Seh_exception_divide_by_zero (const pexception_pointers pexp, STD: String what)

: Seh_exception_base (pexp, what ){};

~ Seh_exception_divide_by_zero () Throw (){};

};

//////////////////////////////////////// ////////////////////////////////////////

//////////////////////////////////////// ////////////////////////////////////////

Class seh_exception_invalid_handle: Public seh_exception_base

{

Public:

Seh_exception_invalid_handle (const pexception_pointers pexp, STD: String what)

: Seh_exception_base (pexp, what ){};

~ Seh_exception_invalid_handle () Throw (){};

};

//////////////////////////////////////// ////////////////////////////////////////

// Callback function when a system exception occurs

// Here is the implementation, which is critical. Throws a C ++ exception for different exceptions.

Void seh_exception_base: trans_func (unsigned int U, exception_pointers * pexp)

{

Switch (pexp-> predictionrecord-> predictioncode)

{

Case exception_access_violation:

Throw seh_exception_access_violation (pexp, "storage protection exception ");

Break;

Case exception_int_divide_by_zero:

Throw seh_exception_divide_by_zero (pexp, "Division by 0 exception ");

Break;

Case exception_invalid_handle:

Throw seh_exception_invalid_handle (pexp, "invalid sentence exception ");

Break;

Default:

Throw seh_exception_base (pexp, "Other seh exceptions ");

Break;

}

}

// Test it!

Void main (void)

{

Seh_exception_base: initialize_seh_trans_to_ce ();

Try

{

// Divide by 0

Int X, Y = 0;

X = 5/y;

// Storage protection

Char * p = 0;

* P = 0;

// Other system exceptions, such as interrupt exceptions

_ Asm int 3;

}

Catch (seh_exception_access_violation & E)

{

Printf ("caught seh_exception. Error cause: % s/n", E. What ());

// Other processing

}

Catch (seh_exception_divide_by_zero & E)

{

Printf ("caught seh_exception. Error cause: % s/n", E. What ());

// Other processing

}

Catch (seh_exception_base & E)

{

Printf ("caught seh_exception. Error cause: % s, error code: % x/N", E. What (), E. exception_code ());

}

}

Summary

So far, with regard to the C ++ Exception Handling Model, various exception handling mechanisms in the C language, the seh principle in the window system, and their usage skills, and the precautions for programmers to use these exception handling mechanisms during programming. The previous articles have made systematic and in-depth discussions and analysis (maybe a lot of errors! Welcome to point out and discuss ). I believe that it is not only the hero of AI, but also those who have carefully read, tasted, and come along with AI. Now they all have a feeling of openness. Thanks for various exception handling mechanisms! Thanks to the talents who have designed such exquisite technologies and works! Thanks to all the programmers in the world!

The Exception Handling Model in Java comes from the shoulders of the C ++ Exception Handling Model. It inherits the style and advantages of the C ++ Exception Handling model, and is more secure, higher, and richer than the C ++ Exception Handling Model. In the next article, the hero, a Yu, plans to pursue the victory and discuss some exception handling models in Java. If you are interested, continue!

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.