C + +: Handling of exceptions

Source: Internet
Author: User

6.4 Exception Handling
Common errors in the program fall into two categories: compile-time errors and run-time errors.

Compile-time errors are relatively simple and easy to find: mainly grammatical errors, such as keyword spelling errors, missing semicolons, parenthesis mismatch, etc.
Runtime errors are more difficult to find, even unpredictable: error algorithms, insufficient memory space, cross-border, file cannot be opened, etc.

There are two ways to deal with exceptions: traditional exception handling methods and system exception handling mechanisms.

The traditional exception processing method features: Is the use of judgment and Branch statement class implementation, suitable for small applications.
System exception handling mechanism features: through detection, throw and catch exceptions to achieve, suitable for a variety of large-scale applications

Example 6.10 Examples of traditional exception handling methods

#include <iostream>using namespaceStd;inlineintDIV (intXinty);intMain () {cout<<"7/3="<<div (7,3) <<Endl; cout<<"5/0="<<div (5,0) <<Endl;return 0;} InlineintDIV (intXinty) { if(y==0) {cout<<"Divisor is 0, error!"<<Endl; Exit (0); } returnx/y;}

Methods of 6.4.2 Exception handling
C + + handles exceptions by: If an exception occurs during the execution of a function, it can not be processed immediately in this function, but instead sends a message to its previous level (that is, the calling function) to resolve, if the upper level can not be processed, and then to the upper level, from the previous level of processing, so step-by-step upload, If it cannot be processed at the highest level, the operating system will normally call the system function terminate, which calls abort to terminate the program.

This method of handling causes the exception to be thrown and the processing mechanism to separate, rather than having the same function complete. The benefit of this approach is that the underlying function (called function) is focused on solving the actual task without having to worry too much about the handling of the exception to relieve the burden of the underlying function and move the task of handling the exception to the upper layer.


C + + handles exceptions by checking, throwing, and capturing 3 parts, each of which is done by 3 statements; try (check),
throw (throw), catch (Catch)

1. Exception throws
Throws an exception using the throw statement, which has the following format:
throw-expression;

If an exception is found in a program, you can use the throw statement to throw an exception to the caller, which is caught by a catch statement that matches it. The expression in the throw statement is the type of exception that can be thrown, and the type of the exception is represented by the type of the expression. For example, exception handling in the previous example:

int DIV (int x,int  y)     {       if(y==0)         throw y;            //        return x/y;       }           Because the type of the variable y is int, when the divisor is 0 o'clock, the throw throws an int type exception

2. Inspection and capture of anomalies
The format of the exception check try statement and capture Catch statement is as follows:

Try     {      Compound statement checked      }catch1)    {      1     }     Catch 2     {      2    } ...         Catch (Exception type declaration N)    {      compound statement n     } for exception handling

For example, exception checking and capturing of the above example:

Try                                       //Check for exceptions{cout<<"7/3="<<div (7,3) <<endl;//Compound statement checkedcout<<"5/0="<<div (5,0) <<Endl; }    Catch(int)//catch exception, exception type int type{cout<<"Divisor is 0, error!"<<endl;//Compound statement for exception handling}

Example 6.11 handles a program with a divisor of 0 exceptions.

#include <iostream>using namespaceStd;inlineintDIV (intXinty);intMain () {Try{cout<<"7/3="<<div (7,3) <<Endl; cout<<"5/0="<<div (5,0) <<Endl;} Catch(inti) {cout<<"i="<<i<<Endl; cout<<"Divisor is 0, error!"<<Endl; cout<<"over\n"; } return 0;} InlineintDIV (intXinty) { if(y==0)   Throwy;returnx/y;}

The result of the program operation is:
7/3=2
Divisor is 0, error!
Over

In this case, the exception is handled as follows:
(1) First, you will need to check, but also easy to cause the exception of the statement or program segment placed in the try block in curly braces.
(2) If no exception occurs during the execution of a compound statement inside a try statement block, the catch clause does not work, continue to the statement that follows the catch clause.

(3) If an exception occurs during the execution of a compound statement (or called a function) within a try block, the throw statement throws an exception message.

(4) The exception information thrown by the throw is passed to the Try_catch structure, and the system looks for a matching catch clause.
(5) After executing the exception-handling statement, the program resumes execution of the statement after the catch clause.

Description
(1) The detected statement or program segment must be placed in a try block, otherwise it will not work.
(2) A compound statement enclosed in curly braces must be useful in the try and catch blocks, even if there is only one statement in the curly braces.
(3) There can be only one try block in a try_catch structure, but it is possible to have multiple catch blocks to match different exception information. in parentheses after a catch, the type name of the exception information is generally written only.

(4) If the type of the exception information is not specified in the Catch statement and the three-point abridged "..." is used, it can capture any the exception information for the type.

(5) In some cases, the throw statement may not include an expression, such as; throw; at this point it throws the exception information that is currently being processed again, giving the previous level of Catch block processing.

(6) C + +, once an exception is thrown, and the program does not capture, then the system calls the system letter number terminate, called by it to abort the program.

Example 6.12 an exception handler with multiple catch blocks.

#include <iostream>using namespacestd;intMain () {DoubleA=2.3; Try {  ThrowA;} Catch(int) {cout<<"The exception happens! integer! "<<Endl; } Catch(Double) {cout<<"The exception happens! Double-precision! "<<Endl; } cout<<"End"<<Endl;return 0; }/*The result of the program operation is: Exception occurred! Double type! End*/

Example 6.13 an exception handler with a truncated point.

#include <iostream>using namespacestd;voidFuncintx) { if(x)Throwx;} intMain () {Try{func (5); cout<<"No here!"<<Endl;} Catch(...) {cout<<"exception occurs! ANY type! "<<Endl; } cout<<"End"<<Endl;return 0; }/*The result of the program operation is: abnormal occurrence! any type! End*/ 

C + +: Handling of exceptions

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.