C + + study notes (15): Exceptions

Source: Internet
Author: User
Tags mathematical functions

C + + 's father Bjarne Stroustrup in the C + + programming Language: The authors of a library can detect runtime errors, but generally do not know how to deal with them (because they are related to the user's specific application), on the other hand, The users of the library know how to handle these errors, but they cannot check when they occur (if they can detect it, they can be processed in the user's code, and not left to the library to discover).
Bjarne Stroustrup said: The basic purpose of providing exceptions is to deal with the above problems. The basic idea is to have a function throw (throw) an exception when it discovers an error that it cannot handle, and then its (direct or indirect) caller can handle the problem.
That's what "C + + Primer" says: Isolate problem detection from problem handling.

Issues to be aware of when using exceptions in C + +:

    1. Performance issues. This generally does not become a bottleneck, but if you are writing a high-performance or real-time demand for more powerful software, you need to consider.
    2. Memory reclamation problems caused by pointers and dynamic allocations: in C + +, dynamically allocated memory is not automatically reclaimed, and if you encounter an exception you need to consider whether the memory is properly reclaimed. In Java, there is basically no need to consider this, there is a garbage collection mechanism really good!
    3. Exception throw list for function: Java is not allowed if a function does not explicitly specify an exception to throw in the exception throw list, but in C + + if you do not specify an exception to throw in the exception throw list in the function, it means that you can throw any exception.
    4. Compile-time in C + + does not check the exception-throwing list of functions. This means that when you write a C + + program, if you throw an exception in the function that is not declared in the exception throw list, the compilation will not error. In Java, the hint of eclipse is really strong and powerful!
    5. In Java, the exception thrown is an exception class, but in C + + you can throw any type and you can even throw an integral type. (Of course, in C + + if you're using an object instead of a reference when you receive in a catch, the object you throw must be able to replicate.) This is the language requirement, not the exception handling requirement.
    6. There is no finally keyword in C + +. Both Java and Python have the finally keyword.

If an exception is found in the program segment of the TRY statement block, including the function in which it was called, and the exception is discarded, the exception can be caught and processed by a catch statement after the try statement block, and the condition that is caught and processed is that the type of the thrown exception matches the exception type of the catch statement.
Because C + + uses data types to differentiate between different exceptions, the value of the expression in the throw statement has no practical significance when judging the exception, and the type of the expression is particularly important.

1 Throwan expression;2 3 Try 4 {  5 contains statements that may throw exceptions;6 }  7 Catch(type name [formal parameter name])//catching specific types of exceptions8 {  9  Ten }   One Catch(type name [formal parameter name])//catching specific types of exceptions A {   -   - }   the Catch(...)//three dots means catch all types of exceptions - {   -}

Example:

1#include <iostream.h>//Include header file2#include <stdlib.h>3  4 DoubleFucDoubleXDoubleY//Defining Functions5 {  6     if(y==0)  7     {  8         ThrowY//Divisor is 0, throws an exception9     }  Ten     returnX/y;//otherwise returns two number of quotient One }   A   - voidMain () - {   the     DoubleRes;  -     Try  //Defining Exceptions -     {   -RES=FUC (2,3);  +cout<<"The result of X/y is:"<<res<<Endl;  -RES=FUC (4,0); An exception occurs and an exception is thrown inside the function +     }   A     Catch(Double)//catching and handling exceptions at     {   -cerr<<"error of dividing zero.\n";  -Exit1);//Exception Exit Program -     }   -}

Exception classes in the standard library:
Like Java, many exception classes are available in the standard library, which are organized by class inheritance. Standard exceptions are organized into eight.
The exception class inheritance hierarchy chart is as follows:

members of the standard exception class:
In the above inheritance system, each class has a constructor, a copy constructor, and an assignment operator overload.
The Logic_error class and its subclasses, Runtime_error classes, and their subclasses, whose constructors are the formal parameters that accept a string type, are used to describe the exception information;
All exception classes have a what () method that returns the value of the const char* type (c-style string) that describes the exception information.

specific description of the standard exception class:
Exception parent class for all standard exception classes
Bad_alloc when operator new and operator new[], request allocation memory fails
Bad_exception This is a special exception, if the function's exception throw list declares the bad_exception exception, when the function throws an exception that is not thrown in the table, this is the call to the unexpected function if the exception is thrown, no matter what type, will be replaced with the bad_exception type
Bad_typeid uses the typeid operator to manipulate a null pointer, which is a class with a virtual function, and throws a Bad_typeid exception
Bad_cast when using dynamic_cast to convert references failed
Ios_base::failureio error occurred during operation
Logic_error logic errors, errors that can be detected before running
Runtime_error run-time errors, errors that can be detected only at run time

Subclass of Logic_error:
Length_error attempts to generate an object that exceeds the maximum length of the type, such as the resize operation of the vector
The domain error of the Domain_error parameter is mainly used in mathematical functions. For example, use a negative value to invoke a function that only operates non-negative numbers
Out_of_range out of valid range
The invalid_argument parameter is not appropriate. In the standard library, this exception is thrown when the Bitset is constructed using a string object and the character in string is not ' 0 ' or ' 1 '

Subclass of Runtime_error:
Range_error calculation results beyond a meaningful range of domains
Overflow_error Arithmetic calculation overflow
Underflow_error Arithmetic calculation underflow

To write your own exception class:

    1. It is recommended that you inherit the standard exception class for your exception class. Because C + + can throw any kind of exception, our exception class can not inherit from the standard exception, but this may cause the program confusion, especially when we have many people in co-development.
    2. When inheriting a standard exception class, you should overload the what and virtual destructors of the parent class.
    3. Because in the process of stack unwinding, to copy the exception type, consider providing your own copy constructor based on the members you add to the class.

C + + study notes (15): Exceptions

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.