Exception handling of C + +

Source: Internet
Author: User
Tags throw exception try catch

Errors in the program are categorized as compile-time errors and run-time errors. Compile-time errors are mainly syntax errors, such as: the end of the sentence without semicolons, parentheses mismatch, keyword errors, etc., such errors are easier to modify, because the compilation system will indicate the error in the first few lines, what error. While runtime errors are not easy to modify, because errors in them are unpredictable or predictable but unavoidable, such as insufficient memory space, or an array out-of-bounds error when calling a function. If you do not take effective precautions against these errors, you will often not get the correct results of the operation, the program is not properly terminated or serious phenomenon of freezing. We refer to the program runtime errors as exceptions, and exception handling is called exception handling. The exception handling mechanism provided in C + + has a clear structure and can guarantee the robustness of the program to some extent.

The process of handling exceptions in C + + is this: in the execution of the program exception, can not be processed in this function, but instead of throwing an error message, pass it to the previous level of the function to resolve, the upper level can not be resolved, and then passed to its upper level, by its upper level processing. By uploading it so that the top level is not able to handle it, the operating system automatically calls the system function terminate, which calls abort to terminate the program. Such an exception-handling method separates exception-throwing from the processing mechanism, rather than processing it in the same function. This makes the underlying function only needs to solve the actual task, without too much consideration of the exception handling, and the exception handling task to the previous layer of function to deal with.

C + + 's exception handling mechanism consists of 3 parts: try (check), throw (throw), catch (catch). Put the required check in the Try module, check the statement error, throw throws an exception, send an error message, catch to catch the exception information, and to be processed. The exception thrown by the general throw is matched to the type of exception caught by the catch. The general format for exception handling is:

Try

{

Checked statements

Throw exception

}

catch (Exception type 1)

{

Statement for exception handling 1

}

catch (Exception type 2)

{

Statement for exception Handling 2

}

...

Let's use the example to illustrate exception handling:

#include "stdafx.h" #include <iostream>template <typename t>t Div (T x,t y) {if (y==0) throw y;//throws an exception return x/y;} int main () {int x=5,y=0;double x1=5.5,y1=0.0;try    {//checked statement        std::cout<<x<< "/" <<y<< " = "<<div (x, y) <<std::endl;        std::cout<<x1<< "/" <<y1<< "=" <<div (x1,y1) <<std::endl;    } catch (int)//exception type    {        std::cout<< ' divisor is 0, calculation error! "<<std::endl;//exception Handling statement    }catch (double)//exception type    {        std::cout<<" divisor is 0.0, calculation error! "<<std::endl;//exception handling statement    }return0;}

  

Results:

Looking at the example code above, perhaps some people will ask, the second double type of division calculation should also throw an exception to Ah, in the actual operation of the process is not so, in fact, the double type division function is not executed at all. The procedures for the above procedure are: Call function div (x, y) When an exception occurs, the function div in the statement "Throw Y" throws an exception, do not go down the return x/y, then catch catch int type of exception and handle the exception, and finally directly execute "return 0". Therefore the function div (x1,y1) and catch (double) {} modules are not executed at all. If we change the value of Y to 1, the result becomes:

If no exception occurs when executing the TRY statement module, the CATCH statement block does not work and the statement that the process goes to continues execution. From the above two results, we know that the first throw of the int type, so find a catch to handle the type, and the second is to throw a double type is found to handle the double type of catch.

Here are some additions to the exception handling: (1) You must enclose the curly braces in the try and catch blocks, even if there is only one statement within the curly braces, and (2) The try and catch must appear in pairs, with only one try block in the try_catch result. However, you can have multiple catch blocks to match different exception information, (3) If you do not specify the type of exception information in the catch block, and use ellipsis "...", it can catch any type of exception information, or (4) if throw does not include any expressions, Indicates that it throws the exception information that is currently being processed and passes it to the catch on the previous layer, and (5) C + + Once an exception is thrown, if the program does not have any capture, then the system will automatically call a system function terminate, which calls abort termination program;

In the end, I'll use an example to summarize what I'm saying today (development tools: VS2010):

#include "stdafx.h" #include <iostream>template <typename t>t Div (T x,t y) {if (y==0) throw y;//throws an exception return x/y;} int main () {int x=5,y=1;double x1=5.5,y1=0.0;try    {//checked statement        std::cout<<x<< "/" <<y<< " = "<<div (x, y) <<std::endl;        std::cout<<x1<< "/" <<y1<< "=" <<div (x1,y1) <<std::endl;    } catch (...) Catch any type of exception    {try        {            std::cout<<] any kind of exception! "<<std::endl;throw;//throws the current handling exception information to the previous layer of catch        }catch (int)//exception type        {            std::cout<<" divisor is 0, calculation error! "<<std::endl;//exception Handling statement        }catch (double)//exception type        {            std::cout<<" divisor is 0.0, calculation error! "<<std::endl;//exception handling statement        }        }    return0;}

  

Results:

When you're in a hurry to date a sister, you'll find that try catch is actually a good thing.

Exception handling of 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.