当前位置:网站首页>STL tutorial 3- exception mechanism
STL tutorial 3- exception mechanism
2022-06-23 04:51:00 【Sleepy snail】
You can skip to the summary
Catalog
2、 Abnormal upward throw , All the way to the top floor
4、 Exception interface declaration
5、 Declaration cycle of exception types and exception variables
7、 The application of inheritance in exceptions
1、 Basic exception syntax
throw , And then the corresponding try.....catch ...

2、 Abnormal upward throw , All the way to the top floor

Exceptions will be thrown up layer by layer , If the exception is thrown to the top level and has not been handled , Then the program will use terminate() To terminate the program ,c++ The exception handling mechanism of is cross functional .
3、 Stack unwinding

therefore throw Is very similar return, In fact, the local variable leaves its workspace , Will automatically call the destructor
4、 Exception interface declaration
Declare... On a function throw Only the specified data type will be thrown , For other data types, an error will be reported .
But below is vs2022 No report error
// Declaring this function will only throw int float char Three types of anomalies , An error will be reported if other items are thrown
void func()throw (int, float, char) {
throw "abc";
}
// You can't throw any exceptions
void func02()throw() {
throw -1;
}
int main() {
try{
func02();
}
catch (char* str) {
cout << str << endl;
}
catch (int e) {
cout << " abnormal " << endl;
}
catch (...) {// Catch all exceptions
cout << " Unknown type exception " << endl;
}
}5、 Throw exception object
- throw There are types of exceptions to , It could be a number 、 character string 、 Class object
- throw There are types of exceptions to ,catch The exception type needs to be strictly matched

class MyExcept {
public :
void what() {
cout << " Throw an exception ";
}
};
void func03() {
throw MyExcept();// An anonymous object was thrown
}
int main() {
try{
func03();
}
catch (MyExcept e) {
e.what();
}
} The following is the addition of something to the object 
There is a memory leak
You need to add a destructor ~MyExcept(){if(error!=NULL)delete[]error;}. And there will be errors when copying

So the normal code is as follows
class MyExcept {
public:
char* error;
public :
MyExcept(char* str) {
error = new char[strlen(str) + 1];
strcpy(error, str);
}
MyExcept(const MyExcept& ex) {
this->error = new char[strlen(ex.error) + 1];
strcpy(this->error, ex.error);
}
MyExcept& operator=(const MyExcept& ex) {
if (this->error != NULL) {
delete[]this->error;
this->error = NULL;
}
this->error = new char[strlen(ex.error) + 1];
strcpy(this->error, ex.error);
}
~MyExcept() {
if (error != NULL)
delete[]error;
}
void what() {
cout << error << endl;
}
};
void func03() {
char* str ;
strcpy(str, " This is an exception ");
throw MyExcept(str);// Threw an exception object
}
int main() {
try{
func03();
}
catch (MyExcept e) {
e.what();
}
}5、 Declaration cycle of exception types and exception variables
The life cycle of the last segment is
throw The anonymous function of will first call the constructor of the exception object , Then be catch Capture calls the copy function ,
Here, the ordinary element exception function will be destructed after processing

The above catch To quote , References are also catch Call the destructor when the process is complete

Replace with a pointer

Since anonymous functions cannot be used , Then you can. new One , Then after the processing is completed, it will be destructed

6、 Exception standard class
Reference resources c++ Standard library exceptions and writing your own exception classes _xujianjun229 The blog of -CSDN Blog

Because the exceptions of the standard library are limited , So you need to write your own exception class
However, the following points should be paid attention to when writing exception classes
① It is suggested that your exception class should inherit the standard exception class . because C++ Any type of exception can be thrown in , So we The exception class of can not inherit from the standard exception , But that could lead to a lot of procedural confusion , Especially when we have many people working together Hair time .
② When inheriting the standard exception class , Should overload the parent's what Functions and virtual destructors .
③ Because in the process of stack deployment , To copy exception types , Then you should consider whether to provide... According to the members you add in the class Own copy constructor
The following is an example of using a standard library exception
Here we use the out_of_range, You can see that it belongs to <stdexcept>, So include that header file

Write your own exception class below , This exception class inherits from exception

7、 The application of inheritance in exceptions
Here is an example that can handle all kinds of exceptions


Note that destructors must be defined, not just declared , So add {}
class BaseMyException {
public:
virtual void what() = 0;
virtual ~BaseMyException() {};
};
class sourceException:public BaseMyException {
public:
virtual void what() {
cout << " Target space is empty " << endl;
}
virtual ~sourceException() {}
};
class tagetException :public BaseMyException {
public:
virtual void what() {
cout << " Target space is empty " << endl;
}
virtual ~tagetException() {}
};
void copy_str(char* taget,const char* source) {
if (taget == NULL)throw sourceException();
if (source == NULL)throw tagetException();
while (*source != '\0') {
*taget = *source;
taget++;
source++;
}
*taget = '\0';
}
int main() {
const char* source = "abncdedf";
char buf[1024] = { 0 };
try
{
copy_str(NULL, source);
}
catch (BaseMyException& e)
{
e.what();
}
cout << buf << endl;
}8、 summary
1、 Abnormal upward throw , All the way to the top floor , The program will be terminated if it is not processed at the top level
2、 Stack unwinding ,throw Is very similar return, Function throw after , Local variables defined by a function are destructed
3、 Exception interface declaration ,void func()throw (int, float, char) {...} After the statement , Only these three exceptions can be thrown in the function , But in windows It doesn't seem to work
4、throw There are types of exceptions to , It could be a number 、 character string 、 Class object , This class object can be a class written by itself , For example, there is a in the class string Variables store messages ,throw Then use the constructor to assign a value to this variable , then catch Call the print function , This class can also be an inherited standard exception class .
5、 There are two ways to use standard library exception classes , The standard library, like article 4, also has a variable , With out_of_range Class, for example , The first is to throw a out_of_range object , namely throw out_of_range(“ Here we assign values to variables ”); The second method is to write a class that inherits the standard library exception class , Define a variable to store information , Write your own constructor to assign values to variables , rewrite what() Method , Rewrite destructors , then catch Use the base class to receive
6、 After exception handling, the object will be destructed , That is, the life cycle of the exception object is catch After that
7、 Write exception classes for various situations , These classes inherit from a base class , stay catch You can only use the base class to receive
边栏推荐
猜你喜欢

Halcon知识:binocular_disparity 知识

美团好文:从预编译的角度理解Swift与Objective-C及混编机制

在Pycharm中使用append()方法对列表添加元素时提示“This list creation could be rewritten as a list literal“的解决方法

DSP7 环境

使用Live Chat促进业务销售的惊人技巧

volatile 与线程的那些事

聊聊 C# 中的 Composite 模式
![Fundamentals of 3D mathematics [16] formulas for uniformly accelerated linear motion](/img/51/5b05694bbd0f4fd01dd26cf55b22c7.png)
Fundamentals of 3D mathematics [16] formulas for uniformly accelerated linear motion

gson TypeAdapter 适配器

Current relay hdl-a/1-110vdc-1
随机推荐
Openjudge noi 1.13 50: several
Pta:7-58 Book audio-visual rental management
C语言刷题随记 —— 自由落体的球
Pta:7-37 student number analysis
第二次作业笔记
AD9使用技巧拾遗
ADR electronic transmission EDI solution of national adverse drug reaction monitoring center
微信小程序实例开发:跑起来
自举驱动、top开关电源、光耦拾遗
关于php里tcp通讯用swoole框架出现的小问题
MySQL导入大文件(可以是百万级,也可以是百级)
OGNL Object-Graph Navigation Language
Chrome调试技巧
反编译
32单片机一个变量多个.c里使用
ApiPost接口测试的用法之------Get
PCB----理论与现实的桥梁
Freemodbus parsing 1
Banner 标语 旗帜
Abnova fluorescent dye 555-c3 maleimide scheme