这一篇主要记录了类模板中使用异常类的知识点
类模板中使用异常类的时候,异常类同样可以进行模板化
下面通过这个小案例来明白这个知识点
#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(); }