C++類模板中使用異常知識點

這一篇主要記錄了類模板中使用異常類的知識點

類模板中使用異常類的時候,異常類同樣可以進行模板化

下面通過這個小案例來明白這個知識點

#include <iostream>
#include <cstring>
using namespace std;

class Error :public exception{


};


template <class T>
class Myerror{

public:
	void showError(){
	   if(std::strcmp(typeid(T).name(),"int") == 0){
	      cout << "int error" << endl;
	   }else if(std::strcmp(typeid(T).name(),"char") == 0){
	      cout << "char error" << endl;
	   }
	}
};

template <class T>
class PrintTest{

public:
	PrintTest(T t){
	  if(t < 10){
		  throw &Myerror<T>();
	  }else if( t < 'B'){
	      throw &Myerror<T>();
	  }

	}

	template<class T>
	class MyPrint{
	public:
		MyPrint(T t){
		  if(t < 20){
			  throw &Myerror<T>();
		  }else if(t < 'B'){
		      throw &Myerror<T>();
		  }
		}
	
	};
};

template<class T>
void testException(T data){
	try{
		PrintTest<T> print2(data);
	}catch(Myerror<T>* error){
		error->showError();
	}
}


template<class T>
void testException2(T data){
	try{
		PrintTest<T>::MyPrint<T> mp(data);
	}catch(Myerror<T>* error){
		error->showError();
	}
}

void main(){

	testException2<char>('A');
	cin.get();
}

std標準異常的使用:

#include <iostream>
#include <stdexcept>

using namespace std;


class Student{
private:
	int *pstart;
public:
	Student(){
		pstart = new int[5];
	}

	int operator[](int index){
	   if(index < 0){
		   throw std::out_of_range("ba la la");
	   }else if(index  < 2){
		   throw std::logic_error("hahahha");
	   }
	   return pstart[index];
	}

};

void main(){
	try{
	Student stu;
	cout << stu[1] << endl;
	}catch(exception ex){
		cout << "error : because of" << ex.what() << endl;
	}

    cin.get();
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章