[C ++ in-depth analysis] 46. Exception handling in C ++ (Part 1)

1 Abnormal concept

Exceptions may occur during the execution of a program. The difference between exceptions and bugs is that exceptions are predictable branches of execution while the program is running. Bugs are errors in the program and are not expected to run. Here are a few common exceptions and bugs.

abnormal

  • Divide by 0 at runtime
  • The external file to be opened does not exist
  • Array access out of bounds

Bug

  • Use wild pointer
  • The heap array is not released after use
  • Selection sort cannot handle arrays of length 0

2 Exceptions in C ++

C ++ has built-in syntax elements for exception handling try ... catch ...

  • The try statement handles normal code logic, and the catch statement handles exceptions
  • The exception in the try statement is handled by the corresponding catch statement

C ++ throws exception information through throw statement

Examples are as follows:
Insert picture description here
The exception thrown by throw in divide will be caught by try… catch…

The exception thrown by throw must be handled by catch. The current function can handle the exception, and the program continues to execute. If the current function cannot handle the exception, the function stops executing and returns. Unhandled exceptions will propagate up the function call stack until they are handled, otherwise the program will be stopped.
Insert picture description here

Programming experiment: A preliminary study of C ++ exception handling

// 46-1.cpp
#include <iostream>
#include <string>
using namespace std;
double divide(double a, double b)
{
    const double delta = 0.000000000000001;
    double ret = 0;
    if ( !((-delta < b) && (b < delta)) )
    {
        ret = a / b;
    }
    else
    {
        throw 0;
    }
    return ret;
}
int main(int argc, char *argv[])
{
    try
    {
        double r = divide(1, 0);
        cout << "r = " << r << endl;
    }
    catch(...)
    {
        cout << "Divide by zero..." << endl;
    }
    return 0;
}

The program first executes the code in the try. The throw in the divide function throws an exception. There is no catch in the function. The exception is returned to the main function and caught by the catch.

Compile and run:

$ g++ 46-1.cpp -o 46-1
$ ./46-1
Divide by zero...

3 try… catch… detail

3.1 One try and multiple catch

The same try statement can keep up with multiple catch statements.

  • The catch statement can be defined as the type of exception handled specifically, and different types of exceptions are handled by different catch statements
  • Any type of exception can be thrown in the try statement
  • catch (…) is used to handle all types of exceptions
  • Any type of exception can only be caught once

Insert picture description here
catch (…) must be placed at the end, strictly matched from top to bottom, including the const attribute.

Programming experiment: abnormal type matching

// 46-2.cpp
#include<iostream>
using namespace std;
void  Demo1()
{
    try
    {
        throw 'c';
    }
    catch(char c)
    {
        cout << "catch(char c)" << endl;
    }
    catch(short c)
    {
        cout << "catch(short c)" << endl;
    }
    catch(double c)
    {
        cout << "catch(double c)" << endl;
    }
    catch(...)
    {
        cout << "catch(...)" << endl;
    }
}

void Demo2()
{
    throw "error";
}
int main()
{
    Demo1();
    try
    {
        Demo2();
    }
    catch(char* s)
    {
        cout << "catch(char* s)" << endl;
    }
    catch(const char* cs)
    {
        cout << "catch(const char* cs)" << endl;
    }
    catch(string ss)
    {
        cout << "catch(string ss)" << endl;
    }
	return 0;
}

The exception in the function Demo1 is caught by the catch in the function. There are four catches that capture char, short, double, and all other types.

The exception in Demo2 is returned to the main function before being caught. The exception handling must be strictly matched, including the const attribute. The thrown exception "error" is caught by catch (const char * cs). To be caught by catch (string ss), throw string ("error");

$ g++ 46-2.cpp -o  46-2
$ ./46-2
catch(char c)
catch(const char* cs)

3.2 try… catch is used for segmentation

  • try… catch is used to separate normal code and abnormal code

The following code is correct
Insert picture description here

3.3 Specify the type of exception that may be thrown

  • In order to improve code readability, you can directly specify the type of exception that may be thrown during function declaration and definition

The following code indicates that the type of exception that the function may throw is int

Insert picture description here
Programming experiment: try ... catch split code, throw specify exception type

// 46-1.cpp
#include<iostream>
using namespace std;

int func(int i, int j) throw(int, char)		// 指定可以抛出int和char异常
{
    if (0 < j && j < 10)
    {
        return i + j;
    }
    else
    {
        throw '0';
    }
}

void test(int i) try				// try…catch 用于分割正常代码与异常代码
{
    cout << "func(i, i) = " << func(i, i) << endl;
}
catch (int i)
{
    cout << "Exception: " << i << endl;
}
catch (...)
{
    cout << "Exception..." << endl;
}

int main(int argc, char* argv[])
{
    test(4);
    test(10);
    return 0;
}

Compile and run:

func(i, i) = 8
Exception...

4 Summary

1. try ... catch ... is a special statement for exception handling in C ++
2. try statement handles normal code logic, catch statement handles exception code logic
3. The same try can
be matched with multiple catch statements 4. Exception handling must be strictly matched and not performed Any type conversion

Published 298 original articles · praised 181 · 100,000+ views

Guess you like

Origin blog.csdn.net/happyjacob/article/details/104600775