C + + exception handling detailed _c language

Source: Internet
Author: User
Tags exception handling throw exception

Errors in the program are divided into compile-time errors and run-time errors. Compile-time errors are mainly grammatical errors, such as: the end of the sentence is not a semicolon, parentheses do not match, keyword errors, etc., such errors are relatively easy to modify, because the compilation system will indicate the error in the first few lines, what error. Run-time errors are not easy to modify because the errors are unpredictable or predictable but unavoidable, such as insufficient memory space, or an array of errors when calling functions. If you do not take effective precautions for these errors, then often will not get the correct results of the operation, the program is not normal termination or serious will appear panic phenomenon. We refer to the error of the program runtime as an exception, and the 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: When an exception is executed in the execution of the program, it can not be handled in this function, but instead throws an error message that is passed to the function at the top level, which cannot be resolved at the upper level, and then passed on to the previous level. This escalation is not possible until the highest level is not processed, and the system function terminate is invoked automatically by the running system, which calls the abort termination program. Such an exception handling method separates the exception throw from the processing mechanism and is not handled in the same function. This makes the underlying function only need to solve the actual task, without too much consideration of the handling of exceptions, and the task of handling the exception to a layer of functions to deal with.

The exception handling mechanism for C + + consists of 3 parts: try (check), throw (throw), catch (capture). Put the statement you want to check in the Try module, check the statement for errors, throw throw an exception, issue an error message, catch the exception information, and handle it. The exception that is thrown by the general throw matches the type of exception caught by the catch. The general format for exception handling is:

Copy Code code as follows:

Try
{
The statement being checked
Throw exception
}
catch (Exception type 1)
{
Statement 1 for exception handling
}
catch (Exception type 2)
{
Statement 2 for exception handling
}
...

Here's an example to illustrate exception handling:
Copy Code code as follows:

#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
{
The statement being checked
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, some people may ask that the second Double-precision type of division calculation should also throw an exception to Ah, in the actual running process is not so, in fact, the double type division function has not been executed. The procedure above is: when invoking function div (x,y), an exception occurs when the statement "Throw Y" in the function Div throws an exception, does not perform return x/y, then catches the int type exception and handles the exception, and then executes "return 0" directly. 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 the Try statement module is executed, the CATCH statement block does not work and the statement from which the process goes continues to execute. From the above two results, we can see that the first throw throws the type of int, so find a catch that handles that type, and the second time you throw a double type, you find a catch that handles the double type.

The following points are added to exception handling : (1) try and catch blocks must be enclosed in curly braces, even if only one statement within the curly braces cannot omit curly braces, (2) try and catch must appear in pairs, and a try_catch result can have only one try block, But 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 Shing "...", it means that it captures any type of exception information, (4) If throw does not include any expressions, Indicates that it throws the exception information that is currently being processed and passes it on to its upper-level catch; (5) Once an exception is thrown in C + +, if the program does not capture any, then the system will automatically call a system function terminate, which calls the abort termination program;

Last but not the same, I'll use an example to summarize what I'm talking about today (development tools: VS2010):

Copy Code code as follows:

#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
{
The statement being checked
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 type of exception!" "<<std::endl;
throw;//throws the current processing exception information to the previous level 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:

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.