C ++ノート4例外処理

C ++例外処理

スローされた例外のデータ型に応じて、対応するキャッチブロックを入力します

void main(){
	try{
		int age = 300;
		if (age > 200){
			throw 9.8;
		}
	}
	catch (int a){
		cout << "int异常" << endl;
	}
	catch (char* b){
		cout << b << endl;
	}
	catch (...){
		cout << "未知异常" << endl;
	}
	system("pause");
}

関数の外に投げる

void mydiv(int a, int b){
	if (b == 0){
		throw "除数为零";
	}
}

void func(){
	try{
		mydiv(8, 0);
	}
	catch (char* a){
		throw a;
	}
}

void main(){
	try{
		func();
	}
	catch (char* a){
		cout << a << endl;
	}
	system("pause");
}

オブジェクトを投げる

例外クラス

class MyException{
	
};

void mydiv(int a, int b){
	if (b == 0){
		throw MyException();
		//throw new MyException; //不要抛出异常指针		
	}
}

void main(){
	try{
		mydiv(8,0);
	}
	catch (MyException& e2){
		cout << "MyException引用" << endl;
	}
	//会产生对象的副本
	//catch (MyException e){
	//	cout << "MyException" << endl;
	//}
	catch (MyException* e1){
		cout << "MyException指针" << endl;		
		delete e1;
	}
	
	system("pause");
}

throwは、関数がスローする例外のタイプを宣言します

void mydiv(int a, int b) throw (char*, int) {
	if (b == 0){
		throw "除数为零";	
	}
}

標準例外(JavaNullPointerExceptionと同様)

class NullPointerException : public exception{
public:
	NullPointerException(char* msg) : exception(msg){

	}
};

void mydiv(int a, int b){
	if (b > 10){
		throw out_of_range("超出范围");		
	}	
	else if (b == NULL){
		throw NullPointerException("为空");
	}
	else if (b == 0){
		throw invalid_argument("参数不合法");
	}
}

void main(){
	try{
		mydiv(8,NULL);
	}
	catch (out_of_range e1){
		cout << e1.what() << endl;
	}
	catch (NullPointerException& e2){
		cout << e2.what() << endl;
	}
	catch (...){

	}

	system("pause");
}

外部例外

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

		}
	};
};

void mydiv(int a, int b){
	if (b > 10){
		throw Err::MyException();
	}
	
}

おすすめ

転載: blog.csdn.net/fxjzzyo/article/details/84400670