29. C + + exception handling

Source: Internet
Author: User
Tags throw exception

C++Exception Handling

An exception is a problem that occurs during the execution of a program. C + + Exceptions are special cases that occur when a program is run, such as an attempt to divide by 0.

Exceptions provide a way to transfer control over a program. C + + exception handling involves three keywords:try, catch, throw.

    • Throw: When the problem occurs, the program throws an exception. This is done by using the throw keyword.
    • catch: The exception is caught by the exception handler where you want to handle the problem. The catch keyword is used to catch exceptions.
    • Try: The code in the try block identifies the specific exception that will be activated. It is usually followed by one or more catch blocks.

If a block throws an exception, the method that catches the exception uses the try and catch keywords. Code in a try block that might throw an exception, the code in the try block is called the protection Code. The syntax for using the Try/catch statement is as follows:

1 Try2 {3    //Protect Code4}Catch(exceptionname E1)5 {6    //Catch block7}Catch(exceptionname E2)8 {9    //Catch blockTen}Catch(exceptionname EN) One { A    //Catch block -}

If a try block throws a different exception in a different context, you can try to list multiple catch statements to catch different types of exceptions.

Throw exception

You can use the throw statement to throw an exception anywhere in the code block. The operand of the throw statement can be an arbitrary expression, and the type of the result of the expression determines the type of exception that is thrown.

The following is an example of an attempt to divide by zero to throw an exception:

1 DoubleDivision (intAintb)2 {3    if(b = =0 )4    {5       Throw "division by Zero condition!";6    }7    return(Ab);8}
Catching exceptions

The catch block follows the try block and is used to catch the exception. You can specify the type of exception you want to catch, which is determined by the exception declaration in parentheses after the catch keyword.

1 Try 2 {3    // Protect Code 4 }catch(exceptionname e)5{6   // code to handle exceptionname exceptions 7 }

The above code captures an exception of type Exceptionname . If you want the catch block to handle any type of exception thrown by the try block, you must use the ellipsis inside the parentheses of the exception declaration ... as follows:

Try {   //  Protect code }catch(...) {  //  code that can handle any exception }

The following is an instance that throws an exception divided by 0 and catches the exception in the catch block.

1#include <iostream>2 using namespacestd;3  4 DoubleDivision (intAintb)5 {6    if(b = =0 )7    {8       Throw "division by Zero condition!";9    }Ten    return(Ab); One } A   - intMain () - { the    intx = -; -    inty =0; -    Doublez =0; -   +    Try { -z =Division (x, y); +cout << z <<Endl; A}Catch(Const Char*msg) { atCerr << msg <<Endl; -    } -   -    return 0; -}

Since we have thrown an exception of type const char* , when we catch the exception, we must use the const char* in the CATCH block. When the above code is compiled and executed, it produces the following results:

Division by Zero Condition!

Exceptions for C + + standards

C + + provides a series of standard exceptions, defined in <exception> , where we can use these standard exceptions in the program. They are organized in a parent-child class hierarchy, as follows:

The following table is a description of each exception that appears in the hierarchy above:

Exception Description
Std::exception The exception is the parent class for all standard C + + exceptions.
Std::bad_alloc The exception can be thrown through new .
Std::bad_cast The exception can be thrown by dynamic_cast .
Std::bad_exception This is useful when dealing with exceptions that cannot be expected in a C + + program.
Std::bad_typeid The exception can be thrown by typeID .
Std::logic_error An exception that can theoretically be detected by reading the code.
std::d omain_error This exception is thrown when an invalid math field is used.
Std::invalid_argument When an invalid argument is used, the exception is thrown.
Std::length_error This exception is thrown when a std::string is created that is too long.
Std::out_of_range The exception can be thrown through methods, such as Std::vector and std::bitset<>::operator[] ().
Std::runtime_error It is theoretically not possible to read the code to detect an exception.
Std::overflow_error This exception is thrown when a mathematical overflow occurs.
Std::range_error This exception is thrown when an attempt is to store a value that is out of range.
Std::underflow_error This exception is thrown when a mathematical underflow occurs.
To define a new exception

You can define new exceptions by inheriting and overloading the exception class. The following example shows how to use the Std::exception class to implement your own exception:

1#include <iostream>2#include <exception>3 using namespacestd;4  5 structMyException: PublicException6 {7   Const Char* What ()Const Throw ()8   {9     return "C + + Exception";Ten   } One }; A   - intMain () - { the   Try -   { -     Throwmyexception (); -   } +   Catch(myexception&e) -   { +Std::cout <<"MyException caught"<<Std::endl; AStd::cout << e.what () <<Std::endl; at   } -   Catch(std::exception&e) -   { -     //Other Errors -   } -}

Execution Result:

1 MyException caught 2 C + + Exception

Here, what() is a public method provided by the exception class that has been overloaded by all child exception classes. This returns the reason that the exception was created.

29. C + + exception handling

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.