小言_互联网的博客

C++(八):异常处理&模板类(泛型类)

331人阅读  评论(0)

#include <stdlib.h>
#include<stdio.h>
#include<iostream>

using namespace std;
//C++异常处理,根据抛出的异常数据类型,进入到相应的catch块中

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

//throw 抛出函数外

void mydiv(int a,int b) {
	if (a==0) {
		throw (char*)"分母不能为0";
	}
}
void func(){
	try {
		mydiv(0, 8);
	}
	catch (char* b) {
		throw  b;
	}
}
void main() {
	try{
		func();
	}catch (char* b){
		cout << b << endl;
	}
	getchar();
}
/***********************************************************************/


//抛出对象
//异常类

class MyException {

};

void mydiv(int a, int b) {
	if (a == 0) {
		throw MyException();
		//throw new MyException();//不要抛出异常指针
	}
}
void main() {
	try {
		mydiv(0, 8);
	}catch (MyException &e) {//最优
		cout << "MyException引用" << endl;
	}
	//会产生对象的副本
	//catch (MyException e) {
	//	cout << "MyException" << endl;
	//}
	catch (MyException* e) {
		cout << "MyException指针" << endl;
		delete e;
	}
	getchar();
}
/***********************************************************************/



//throw声明函数会抛出的异常类型

void mydiv(int a, int b) throw(char*,int){
	if (a == 0) {
		throw (char*)"分母不能为0";
	}
}
/***********************************************************************/


#include <stdexcept>
//标准异常(类似于JavaNullPointerException)

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

	}
};
void mydiv(int a, int b)  {
	if (a == 0) {
		throw out_of_range((char*)"分母不能为0");
	}
	if (b == NULL) {
		throw NullPointerException((char*)"参数不合法");
	}
	if(b==0){
		throw invalid_argument((char*)"b==0");
	} 
}

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

	}

	getchar();
}
/***********************************************************************/


//外部类异常

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

		}
	private:

	};
};
void mydiv(int a, int b) {
	if (a == 0) {
		throw Err::MyException();
	}
	
}
/***********************************************************************/



//模板类
template<class T>
class A{
public:
	A(T a) {
		this->a = a;
	}
protected:
	T a;
};

//继承模拟板类
class B :public A<int> {
public :
	B(int a,int b) :A<int>(a) {
		this->b = b;
	}
private:
	int  b;
};


//模板类继承模板类
template<class T>
class C :public A<T> {
public:
	C(T a,T c) :A<T>(a) {
		this->c = c;
	}
protected:
	T c;
};

void main() {
	//实例化模板类对象
	//List<String> list;
	A<int> a(6);
	system("pause");
}

转载:https://blog.csdn.net/huangxiaoguo1/article/details/101028932
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场