C++ 标准异常类
2015-01-30 20:39
211 查看
1、bad_alloc:
4、继承标准异常类
#include <iostream> #include <new>//new 头文件里有异常类 using namespace std; class Dog { public: Dog() { parr = new int[1000000]; } private: int *parr; }; int main() { Dog *pDog; try{ for(int i=1; i<10000; i++) { pDog = new Dog(); cout << i << ":new Dog 成功" << endl; } } catch(bad_alloc err)//new分配内存失败 { cout << "new Dog 失败:" << err.what() << endl; } }2、invalid_argument
#include <iostream> #include <bitset> #include <string> using namespace std; int main() { try { string s("10ab110010"); bitset<10> b(s); cout << "bitset ok" << endl; } catch(invalid_argument err) { cout << "bitset error:" << err.what() << endl; } return 0; }3、out_of_range
#include <iostream> #include <stdexcept> using namespace std; class 学生 { public: 学生(int 年龄) { if(年龄<0 || 年龄>150) throw out_of_range("年龄不能小于0或大于150"); this->m_年龄 = 年龄; } private: int m_年龄; }; int main() { try{ 学生 张飞(220); cout << "学生没错" << endl; } catch(out_of_range err) { cout << "学生出错" << err.what() << endl; } }
4、继承标准异常类
//Stack.h #ifndef STACK_H #define STACK_H #include <exception> #include <deque> template<class T> class Stack { protected: std::deque<T> c; public: class ReadEmptyStack : public std::exception { public: virtual const char * what() const throw()//后面这个throw()表明该方法不会抛出异常 { return "read empty stack 堆栈是空的"; } }; bool empty() const { return c.empty(); } void push(const T& elem) { c.push_back(elem); } T pop() { if(c.empty()) { throw ReadEmptyStack(); } T elem(c.back()); c.pop_back(); return elem; } T& top() { if(c.empty()) { throw ReadEmptyStack(); } return c.back(); } }; #endif
//main.cpp #include <iostream> #include "Stack.h" using namespace std; int main() { try { Stack<int> st; st.push(1); st.pop(); st.pop(); } catch(const exception& e) { cerr << "发生异常" << e.what() << endl; } return 0; }
相关文章推荐
- C++ 标准库中的异常
- c++标准异常类别
- C++ 标准异常
- C++ 标准库中的异常
- C++中的标准异常类
- c++ 标准异常
- C++ 标准的异常
- c++ 抛出标准异常
- c++ 11 国标标准方面的异常处理与微软在Visual Studio 2012的异常处理的区别
- C++ - 标准异常报错(call to 'std::exception::exception(const char [n])')
- 浅谈C++ 标准库中的异常 —— stdexcept类
- C++ 11 国标标准方面的异常处理与微软在Visual Studio 2012的异常处理的区别
- MFC异常 与C++标准异常
- C++标准异常
- C++ 标准库中的异常 http://blog.csdn.net/hzhxxx/article/details/7616336
- C++ 标准库中的异常
- c++标准异常类别
- C++标准异常类
- c++ 标准异常类
- C++中的标准异常类