## exception handling

Like Java, C++ has exception handling.

### Exception type

In C++, the types of exceptions are arbitrary, as follows:

void main(){ try{ //throw 1; //throw "exception message "; Throw 9.8; } catch (int a){cout << "int exception: "<< a << endl; } catch (char* s){cout << "char* exception: "<< s << endl; } catch (...) {cout << "unknown exception "<< endl; } system("pause"); }Copy the code

Throw different types of exceptions that are caught in the corresponding catch block. Among them… Can catch all types of exceptions, catch order, if caught first, later catch block will not execute.

### keep throwing it out

When an exception is thrown inside a function, it can be thrown layer after layer, and if there is no catch, the program will stop. We can declare a list of the types of exceptions thrown at function definition time.

Void fun1() throw(char*){throw "I am an exception "; } void main(){ try{ fun1(); } catch (char* s){cout << "char* exception: "<< s << endl; } system("pause"); }Copy the code

C++ standard exceptions and custom exceptions

C++ provides a standard set of exception classes, such as the following out_of_range:

#include <stdexcept> void fun1() throw(out_of_range){throw out_of_range(" out of range "); } void main(){ try{ fun1(); } catch (out_of_range err){cout << "out_of_range exception: "<< err.what() << endl; } system("pause"); }Copy the code

We can also customize exceptions:

Custom exceptions need to inherit from the Exception class.

class MyException :public exception{ public: MyException(char* msg) :exception(msg){ } }; Void fun1() throw(MyException){throw MyException(" custom exception "); } void main(){ try{ fun1(); } //catch (MyException err){// cout << "MyException exception: "<< err.what() << endl; Catch (MyException &err){cout << "MyException: "<< err.what() << endl; } system("pause"); }Copy the code

The following statement throws an exception pointer:

Throw new MyException(" custom exception pointer ");Copy the code

A pointer is required when capturing:

Catch (MyException *err){cout << "MyException: "<< (*err).what() << endl; }Copy the code

However, we generally do not recommend throwing exception Pointers, because new classes exist in the heap, and we need to delete them manually.

Throw an exception for the inner class

class Err{
public:
	class MyException{
	public:
		MyException(){}
	};
};


void fun1() throw(Err::MyException){
	throw Err::MyException();
}
Copy the code

If you feel that my words are helpful to you, welcome to pay attention to my public number:

My group welcomes everyone to come in and discuss all kinds of technical and non-technical topics. If you are interested, please add my wechat huannan88 and I will take you into our group.