Several common problems with exception handling

table of Contents

 

Common problems with exception handling

What is the purpose of exception handling?

How to use exception handling?

If an exception is thrown, will the execution continue downward?

Sample code

operation result

Result analysis

If an exception is thrown, how to deal with the member variables in its scope?

Code example

operation result

Result analysis

In summary, what is the execution flow of exception handling?

How to pass a custom exception?

How to customize exception handling through inheritance?

Three should and three should not be when writing exception handlers


Common problems with exception handling

What is the purpose of exception handling?

In fact, exception handling is implemented using try-catch statements and exception handling flags. Try is used to catch exceptions, and catch is used to catch exceptions and deal with them accordingly. When we encounter abnormal statements, try-catch can be used to realize abnormal recognition. For example, we usually apply for memory space dynamically with new, but what if the application space is too large and the computer memory is not used? To accurately identify this kind of error, we can use the try-catch statement to achieve, see the routine of "How to use exception handling?" for details.

How to use exception handling?

Used to identify specific anomalies:

#include <exception>  
#include <iostream>  
using namespace std;  
  
int main()  
{  
    try  // 用于识别try{}语句块中的异常并且抛出异常
    {  
        int Size;  
        cin >> Size;  
        int *ArrayPointer = new int[Size];  // 我输入-1,出现bad_alloc异常
        delete[] ArrayPointer;  
    }  
    catch (bad_alloc& exp)  // 被相应的catch语句捕获
    {  
        cout << exp.what() << endl;  
    }  
    catch (exception& exp)  // 用于捕获除bad_alloc之外的异常
    {  
        cout << exp.what() << endl;  
    }  

 

If we identify all anomalies, then we can simplify the above steps:

#include <exception>  
#include <iostream>  
using namespace std;  
  
int main()  
{  
    try  
    {  
        int Size;  
        cin >> Size;  
        int *ArrayPointer = new int[Size];  
        delete[] ArrayPointer;  
    }  
    catch (exception& exp)  
    {  
        cout << exp.what() << endl;  
    }  
}  

 

If an exception is thrown, will the execution continue downward?

Sample code

#include <exception>  
#include <iostream>  
using namespace std;  
  
int main()  
{  
    try // 用于识别try{}语句块中的所有异常并且抛出异常  
    {  
        int Size;  
        cin >> Size;  
        int *ArrayPointer = new int[Size];  
        cout << "正在继续执行" << endl; // 不会继续向下执行,直接由catch捕获异常然后执行处理程序  
        delete[] ArrayPointer;  
    }  
    catch (bad_alloc& exp) // 用于捕获bad_alloc特定异常  
    {  
        cout << exp.what() << endl;  
    }  
    catch (exception& exp) // 用于捕获除bad_alloc之外的其他所有异常  
    {  
        cout << exp.what() << endl;  
    }  

 

operation result

 

Result analysis

We see in the results that when an exception is thrown, it will be caught by catch and executed in the catch exception handler.

If an exception is thrown, how to deal with the member variables in its scope?

Code example

#include <exception>  
#include <iostream>  
using namespace std;  
  
struct Mumber_A   
{  
    Mumber_A()  
    {  
        cout << "调用构造函数" << endl;  
    }  
    ~Mumber_A()  
    {  
        cout << "调用析构函数" << endl;  
    }  
};  
  
void ExceptionShow()  
{  
    Mumber_A Obj_A;  
    throw "出现异常";  
}  
  
int main()  
{  
    try  
    {  
        ExceptionShow();  
    }  
    catch (const char* Obj)  
    {  
        cout << "异常处理" << endl;  
    }  
    cout << "主程序结束" << endl;  
}  

 

operation result

 

Result analysis

We can see through the running results that when the try{} statement block throws an exception, the first thing to do is to deconstruct all objects in the try{} statement block, and then jump to the catch to execute the exception handler.

From the results, when an exception is thrown, it will be immediately caught by catch and enter the catch exception handler.

In summary, what is the execution flow of exception handling?

 

How to pass a custom exception?

#include <iostream>  
#include <exception>  
using namespace std;  
  
void ExceptionShow1()  
{  
    throw "抛出异常";  
}  
  
void ExceptionShow2()  
{  
    ExceptionShow1();  
    throw; // 继续抛出异常  
}  
  
int main()  
{  
    try  
    {  
        ExceptionShow2 ();  
    }  
    catch (const char* exp)  // 捕捉ExceptionShow2抛出的异常
    {  
        cout << "异常处理程序" << endl;  
    }  
}  

 

How to customize exception handling through inheritance?

#include <iostream>  
#include <exception>  
#include <string>  
using namespace std;  
  
class CustomException : public exception  
{  
private:  
    string reason;  
public:  
    CustomException(string reason)  
    {  
        this->reason = reason;  
    }  
    ~CustomException()  
    {  
        cout << "调用CustomException的析构函数" << endl;  
    }  
    virtual const char* what() const noexcept // throw()与noexcept等价,表明:在这个函数作用域内不可以抛出任何异常  
    {  
        return reason.c_str(); // 重载虚函数时,子类与父类各方面都必须一样  
    }  
};  
double Division(double divisor,double dividend)  
{  
    if (dividend == 0)  
    {  
        throw CustomException("除数为零");  
    }  
    return divisor / dividend;  
}  
  
int main()  
{  
    try  
    {  
        cout << "结果为" << Division(8, 0) << endl;  
    }  
    catch (exception& exp)  // 一定要用引用
    {  
        cout << exp.what() << endl;  
    }  
}  

The best way to customize exception handling is to inherit the exception, because this can ensure that a custom exception flag is added on the basis of reusing all exception flags of the exception.

What are the advantages of custom exception handling?

Of course, this is not necessary, but it allows you to reuse all catch() blocks that catch std::exception exceptions. When writing your own exception class, you can not inherit any class, but you must insert a new catch (MyNewExceptionType&) statement in all relevant places.

Three should and three should not be when writing exception handlers

 

Guess you like

Origin blog.csdn.net/weixin_45590473/article/details/108307581