Custom C ++ Exception Handling

Source: Internet
Author: User

Example 1: Define an exception class myexception that inherits from mongoton.

In the C ++ standard, any exception class defined in <stdexcept> is derived from the exception class. In this example, it is simply inherited by exception, and an exception is thrown and captured in the try section. The Code is as follows:

/*++ test.cppversion:1.0decript:define a exception class named myExceptionderived from base class exceptionwhich is declared in <exception>created:2011-08-14author:btwsmile--*/#include<exception>#include<iostream>using namespace std;//customized exception class 'myException'class myException:public exception{public:myException():exception("ERROR! Don't divide a number by integer zero.\n"){}};//entry of the applicationint main(){int x=100,y=0;try{if(y==0) throw myException();else cout<<x/y;}catch(myException& me){cout<<me.what();}system("pause");return 0;}

The result is as follows:
Error! Don't divide a number by integer zero.
Press any key to continue...

Apparently, exceptions are caught. Note that VC extends the exception handling class exception. In this example, exception ("error !.... ") For this reason, the C ++ standard does not allow this.

At the same time, VC does not follow the standard and strongly supports terminate and unexpected. It only retains the syntax, but does not support it during compilation and runtime. The following example uses Dev CPP ide To learn more about C ++ Exception Handling in combination with terminate and unexpected.

Example 2: implement the custom exception class myexception according to the C ++ standard and encapsulate the throw statement into the function check ().

As described in the title, (1) rewrite the what () function of the base class and return the error message; (2) encapsulate throw myexception () into the check () function; (3) Allow the check () function to throw an exception of the myexception type. The Code is as follows:

/*++ test.cppversion:1.1decript:define a exception class named myException         according to C++ standard,derived from base class exceptionwhich is declared in <exception>!also,encapusulate throw into a functioncreated:2011-08-14author:btwsmile--*/#include<exception>#include<iostream>using namespace std;//customized exception class 'myException'class myException:public exception{public:   const char* what()const throw()//#1    {        return "ERROR! Don't divide a number by integer zero.\n";   }    };void check(int y) throw(myException)//#2{     if(y==0) throw myException();}//entry of the applicationint main(){int x=100,y=0;try{check(y);cout<<x/y;}catch(myException& me){cout<<me.what();}system("pause");return 0;}

The result is exactly the same as that in Example 1. Note that the throw list after check () indicates the exception type that can be thrown by the function. I have to raise a question here. What if an unsupported exception type is thrown?

Example 3: A unexpected exception is thrown.

Check the throw list after the function body, specifying the types of exceptions that can be thrown. Unexpected is triggered once the exception is violated. You can regard unexpected as the callback function automatically called by the system. The difference is that it can also be manually triggered for execution. In this example, the former is used. The Code is as follows:

 

/*++ test.cppversion:1.3decript:define an unexpected excption handler,        set it by using set_unexpected,        modify the throw list of function checkcreated:2011-08-14author:btwsmile--*/#include<exception>#include<iostream>using namespace std;//customized exception class 'myException'class myException:public exception{public:   const char* what()const throw()   {        return "ERROR! Don't divide a number by integer zero.\n";   }    };void check(int y) throw()//#1 only int-type exception is permitted{     if(y==0) throw myException();}void myUnexpected(){     cout<<"Unexpected exception caught!\n";     system("pause");     exit(-1);}//entry of the applicationint main(){    unexpected_handler oldHandler=set_unexpected(myUnexpected);int x=100,y=0;try{check(y);cout<<x/y;}catch(myException& me){cout<<me.what();}system("pause");return 0;}

The result is as follows:

Unexpected exception caught!
Press any key to continue...

The throw list of the check function is empty, that is, it is not allowed to throw any type of exceptions. However, when an exception occurs, the system cannot wait and it will call the unexpected processing method. Therefore, limiting a function throw list to NULL is worth the attention of programmers. If you change the code at #1 to throw (INT), you can get the same result. The so-called unexpected exception. To put it bluntly, the function body can throw an exception out of the exception type range. If the check function does not have throw at all, it indicates that all types of exceptions of the function are allowed.

Example 4: An exception allowed by the function body is thrown but not captured.

Think about this problem. If the throw list of the Function check contains the exception type myexception, and when y = 0, it does throw the exception of the myexception type but is not caught, what will happen at this time?

Before officially answering this question, we should first discuss the meaning of "not caught. For example, the Code for modifying Example 3 is as follows)

/*++ test.cppversion:1.4.1decript:        how to understand "exception not caucht"?created:2011-08-14author:btwsmile--*/#include<exception>#include<iostream>using namespace std;//customized exception class 'myException'class myException:public exception{public:   const char* what()const throw()   {        return "ERROR! Don't divide a number by integer zero.\n";   }    };void check(int y) //any type of exception is permitted{     if(y==0) throw myException();}void myUnexpected(){     cout<<"Unexpected exception caught!\n";     system("pause");     exit(-1);}//entry of the applicationint main(){    unexpected_handler oldHandler=set_unexpected(myUnexpected);int x=100,y=0;try{check(y);cout<<x/y;}catch(int &e) //##1 no catch sentence matches the throw type{cout<<e<<endl;}/*               ##2 if add this part, any type which's not handler before will                    be caughtcatch(...){                    cout<<"Unkown exception caught!\n";         }    */system("pause");return 0;}

During compilation and running, the program will encounter errors because the myexception exception thrown by the check function is not handled. By default, the system will automatically call the abort () function to terminate the program's permission if an exception is thrown and not handled:
This application has requested the runtime to terminate it in an unusual way. Please contact the application's Support Team for more information.

However, you can add the #2 part of the code. Catch (...) indicates capturing any type of exception.

Note: The types of exceptions not allowed by the check function are not included in the judgment of the catch statement. Therefore, catch (...) has no effect on unexpected exception.

We still consider the absence of #2. As described above, the system will automatically call the abort () function to terminate the program. Actually, it triggers terminate. Similar to unexpected, you can still customize the terminate processing method. Even terminate syntax is very similar to unexpected. Modify the code:

/*++ test.cppversion:1.4.2decript:        how to understand "exception not caucht"?created:2011-08-14author:btwsmile--*/#include<exception>#include<iostream>using namespace std;//customized exception class 'myException'class myException:public exception{public:   const char* what()const throw()   {        return "ERROR! Don't divide a number by integer zero.\n";   }    };void check(int y) //any type of exception is permitted{     if(y==0) throw myException();}void myUnexpected(){     cout<<"Unexpected exception caught!\n";     system("pause");     exit(-1);}void myTerminate() //##1 set it be the terminate handler{     cout<<"Unhandler exception!\n";     system("pause");     exit(-1);}//entry of the applicationint main(){    unexpected_handler oldHandler=set_unexpected(myUnexpected);    terminate_handler preHandler=set_terminate(myTerminate);int x=100,y=0;try{check(y);cout<<x/y;}catch(int &e) //no catch sentence matches the throw type{cout<<e<<endl;}system("pause");return 0;}

The result is as follows:

Unhandler exception!
Press any key to continue...

Conclusion:C ++ provides friendly support for exception handling.

You can customize the exception type. The exception type is not limited. It can be a built-in data type such as Int or double, or a custom class, it can also be inherited from an exception class in C ++. Example 1 uses the method derived from exception.

When defining a function, you can explicitly specify the exception type thrown by the function body. By default, functions are allowed to throw any type of exceptions. You can add throw statements to limit the exception type. Specifically, throw () indicates that the function is not allowed to throw any type of exception. If the exception type specified in the throw list is violated, the system calls unexpected hanlder to process the exception. You can customize the unexpected exception handling method. Examples 2 and 3 illustrate them.

If an exception that is valid in the throw list of the function body is thrown but not captured by the program, the system calls terminate handler for processing. By default, you can simply call the abort () function to terminate the program. You can also customize the terminate processing method. Example 4 describes it.

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.