您的位置:首页 > 编程语言 > C语言/C++

C++ 标准异常类

2015-01-30 20:39 211 查看
1、bad_alloc:

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: