Exceptions in C + +

Source: Internet
Author: User

One, the abnormal deduction

1. Functions and exceptions

Normally when we have an exception in the function, we usually terminate the function by return and return a value, then get the value on top of the function and determine what is the exception. Because the function is a stack structure, the return time is through the stack structure gradually upward, can not be thrown across functions directly, inconvenient. So C + + introduced the exception mechanism, through the exception mechanism we can easily catch the exception to occur.

Basic demo of exception in 2.c++

# include<iostream>using namespacestd;/*defines the quotient function, if the divisor is 0, throws a double type exception*/DoubleDivDoubleD1,DoubleD2) {    if(D2 = =0)    {        ThrowD2; }    returnD1/D2;}intMain () {/*try...catch statements to catch exceptions*/    Try    {        Doubleresult = Div (1.02,0.0); }    Catch(Doublee) {/*exceptions in C + + are strict with type matching, that is, what exception is thrown to catch what type of exception*/cout<< e <<"no divisor"<<Endl; }    Catch (...) {cout<<"Unknown Exception"<<Endl; }    return 0;}

Summary of exceptions in 3.c++

    • The exception captures strictly match the data type, does not support type auto-conversion, the throw is the int type, and the catch must be of type int otherwise it will not match.
    • Generally we add catch (...) at the end of the exception. This enables the capture of arbitrary exceptions.

Second, custom exception class

1. Exception classes

According to the object-oriented thinking, our exception should also be an object, so when throwing an exception, we usually customize an exception class, and then put the exception information into the exception class, and then when the exception object is caught, then call the object's methods to print out the exception information.

2. Exception Class Code Demo

# define _crt_secure_no_warnings# include<iostream>using namespacestd;/*Custom Exception Classes*/classmyexception{Private:    Char*content; Public:    /*Exception class Constructors*/MyException (Const Char*content) {         This->content =New Char[Strlen (content) +1]; strcpy ( This-content, content); cout<<"exception class with parameter constructor execution"<<Endl; }    /*Exception class copy constructors*/MyException (Constmyexception&me) {         This->content =New Char[Strlen (Me.content) +1]; strcpy ( This-content, me.content); cout<<"Exception class copy constructor execution"<<Endl; }    /*Exception class destructor*/~myexception () {if( This->content! =NULL) {            Delete[] This-content;  This->content =NULL; } cout<<"destructor execution for an exception class"<<Endl; }    /*Exception class throws exception information*/    voidtoString () {cout<< This->content <<Endl; }};/*define a function for testing exceptions*/DoubleDivideDoubleD1,DoubleD2) {    if(D2 = =0)    {        ThrowMyException ("the divisor cannot be 0"); //throw new MyException ("divisor cannot be 0");    }    returnD1/D2;}intMain () {Try    {        Doubleresult = Divide (1,0); cout<<"result ="<< result <<Endl; }    Catch(MyException e) {//catch exceptions are element types, execute copy constructors, have two exception objects, release two exception objects, unreasonablee.tostring (); }    Catch(MyException *e) {//catch exception is a pointer type, we must call the Delete method manually to call the destructor, unreasonableE->toString (); Deletee; }    Catch(myexception&e) {//catch is a reference type, an object that was originally thrown, the destructor is automatically executed, and we use the reference to receive the thrown exception objecte.tostring (); }    Catch (...) {cout<<"Unknown Exception"<<Endl; }    return 0;}

3. Summary of Custom exception classes

    • Throwing an exception object is usually a reference to catch this object, if it is an element catch exception object will execute copy constructor, create two duplicate exception object and free two times object, so unreasonable. If the catch is a pointer type, the destructor that does not automatically call the object must be manually delete and does not conform to the automatic invocation logic, so a reference is used to catch the exception object.

Third, Standard exception class

1. Standard Exception class

Standard exception classes are provided in C + + and require # INCLUDE<EXCEPTION> The standard exception class is exception, which has a what function that can print exception information for an exception object. The what function is a virtual function, we need to inherit the exception class and rewrite the what function, when catching an exception, we use the parent class reference to receive the custom standard exception class subclass object (type compatibility principle), and then print the exception information.

2. Standard Exception class Demo

# include<iostream># include<exception>using namespacestd;/*inherit from standard exception class*/classDivexception: Publicexception{Private:    Const Char*ptr; Public:    /*constructor receives exception information*/Divexception (Const Char*ptr) {         This->ptr =ptr; }    /*Rewrite what function*/     Virtual Char Const* What ()Const{cout<< This->ptr <<Endl; returnptr; }};/*Test Exception function*/intDiviintAintb) {    if(b = =0)    {        ThrowDivexception ("the divisor cannot be 0"); }    returnAb;}intMain () {Try{divi (Ten,0); }    Catch(exception&e) {/*to receive a custom subclass object using the exception reference*/E.what (); }    Catch (...) {cout<<"Unknown Exception"<<Endl; }    return 0;}

Exceptions in C + +

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.