C + + Learning 39 Getting Started with exception handling (try and catch)

Source: Internet
Author: User
Tags throw exception

The compiler guarantees that the syntax of the code is correct, but does nothing about logic errors and run-time errors, such as a divisor of 0, memory allocation failure, array out of bounds, and so on. If these errors are left unchecked, the system will perform the default operation, terminating the program, which is what we often call a program crash (Crash).

A good programmer can recover from a failure or prompt the user for something, and an irresponsible programmer will let the program crash. C + + provides an exception mechanism that allows us to capture logic errors and run-time errors, and make further processing.

An example of a program crash:

#include <iostream>using namespacestd;intMain () {stringstr ="C plus plus"; CharCH1 = str[ -];//Subscript is out of bounds, ch1 is garbage valuecout<<ch1<<Endl; CharCH2 = str.at ( -);//Subscript out of bounds, throws an exceptioncout<<ch2<<Endl; return 0;}

Run the code and the program crashes after the console outputs the CH1 value. Let's take a look at the analysis.

At () is a member function of the string class that returns one character of the string according to the subscript. Unlike "[]", at () checks if the subscript is out of bounds, throws an exception (error) If it is out of bounds, and "[]" does not check, regardless of how much of the subscript will be accessed as usual.

In the above code, subscript 100 is clearly beyond the length of the string str. Because the 6th line of code does not check for subscript out-of-bounds, there are logic errors, but the program works correctly. The 8th line of code is different, the at () function detects that the subscript out of bounds throws an exception (that is, an error), this exception should be handled by the programmer, but we do not process in the code, so the system can only perform the default operation, terminate the program execution.

Catching exceptions

In C + +, we can catch the above exception and avoid the program crashing. The syntax for catching exceptions is:

Try {    //  The statement that could throw an exception }catch(Exception type    ) {//  statement handling exception }

The try and catch are all keywords in C + +, followed by a statement block, and cannot be omitted "{}". The try contains statements that may throw exceptions that are caught if an exception is thrown. As you can see from the "try", it just "tries" to catch an exception, and if no exception is thrown, then nothing is caught. Catch is used to handle the exception that the try captures, and if the try does not catch an exception, the statement in the catch is not executed.

Modify the above code to include the statement that catches the exception:

#include <iostream>using namespacestd;intMain () {stringstr ="C plus plus"; Try{        CharCH1 = str[ -]; cout<<ch1<<Endl; }Catch(Exception e) {cout<<"[1]out of bound!"<<Endl; }    Try{        CharCH2 = str.at ( -); cout<<ch2<<Endl; }Catch(Exception e) {cout<<"[2]out of bound!"<<Endl; }    return 0;}

As you can see, the first try did not catch an exception and output a garbage value. Because "[]" does not check for subscript out of bounds, no exception is thrown, so even if there is a logic error, try nothing is caught.

The second try catches the exception and jumps to the catch, executing the statement in the catch. It is necessary to note that once thrown, the exception is immediately captured, and the statement following the exception point is no longer executed. This example throws an exception in the 15th row of the at () function, and the cout statement after it is no longer executed, and the output is not visible.

Exception type

The so-called throw exception, in fact, is to create a data, this data contains the error message, the programmer can be based on this information to determine what the problem is, what to do next.

Since the exception is a piece of data, then there should be a data type. C + + Specifies that an exception type can be a basic type, a type of a class in a standard library, or a type of a custom class. The exception that is thrown by the C + + language itself and by functions in the standard library is the type of the exception class or its subclasses. In other words, when an exception is thrown, an object of the exception class or its subclasses is created.

When an exception is caught, it is compared to the type that the catch can handle, and if it matches the catch type exactly, or if it is a subclass of it, it is given to the current catch block processing. The type given in parentheses after a catch is the type of exception it can handle. In the above example, the exception type that the catch can handle is the Exception,at () function that throws the type Out_of_range,out_of_range is a subclass of exception, so it is handed to this catch block for processing.

The catch exception e can be divided into two parts: exception is the exception type and E is the object of the exception class. When an exception is thrown, the system creates a Out_of_range object and then passes the object as an argument, like a function, to the formal parameter e, so that E is available in the catch block.

In fact, a try can be followed by multiple catch, in the form of:

 try  {   "  catch   (Exception_type_1) { // Span style= "color: #008000;" The statement that handles the exception   catch   (exception_type_2) { //  statements handling Exceptions     ...  catch   (Exception_type_n) { //  The statement that handles the exception } 

When an exception is caught, it is compared to exception_type_1, and if the exception type is exception_type_1 or its subclass, the code in the current catch is executed, and if not, the comparison with the exception_type_2 ... And so on until Exception_type_n. If no matching type is found, it can only be handed over to the system for processing and terminating the program.

Examples of multiple catch blocks:

#include <iostream>#include<exception>#include<stdexcept>using namespacestd;//Custom Error TypesclassMyType: Publicout_of_range{ Public: MyType (Const string&what_arg): Out_of_range (What_arg) {}};intMain () {stringstr ="C plus plus"; Try{        CharCH1 = str.at ( -); cout<<ch1<<Endl; }Catch(myType) {cout<<"error:mytype!"<<Endl; }Catch(out_of_range) {cout<<"error:out_of_range!"<<Endl; }Catch(Exception) {cout<<"error:exception!"<<Endl; }    return 0;}

The try catches the exception and compares with the first catch, because the exception type is Out_of_range,mytype is a subclass of Out_of_range, so the match fails; continue to match down, find the second catch appropriate, match the end; the third catch will not be Yes.

It is important to note that only the exception type is given in parentheses after the catch, and there is no so-called "formal parameter", which is legal. If you do not need to use the error message in the catch, you can omit the parameter.

C + + Learning 39 Getting Started with exception handling (try and catch)

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.