
C++ 在 <exception> 中提供了一系列标准的异常,我们可以用在我们的程序中。这些异常使用父-子分层结构展示如下:

这是对上面提到的层次结构中每个异常的描述:
std::exceptionstd::bad_allocnew 关键字时抛出。std::bad_castdynamic_cast 抛出。std::bad_exceptionstd::bad_typeidtypeid 抛出。std::logic_errorstd::domain_errorstd::invalid_argumentstd::length_errorstd::string 被创造时,抛出异常。std::out_of_rangestd::vector 和 std::bitset::operator[]()。std::runtime_errorstd::overflow_errorrstd::range_errorstd::underflow_error你可以采用继承及重写异常类来。下面是示例,显示如何使用 std::exception 类以标准的方式实现自己的异常:
#include <iostream>
#include <exception>
using namespace std;
struct MyException : public exception {
const char * what() const throw() {
return "C++ Exception";
}
};
int main() {
try {
throw MyException();
} catch(MyException& e) {
std::cout << "MyException caught" << std::endl;
std::cout << e.what() << std::endl;
} catch(std::exception& e) {
//Other errors
}
}这将产生如下的结果:
MyException caught
C++这里,what()是一个异常类提供的公共方法,所有子异常类都覆盖了该方法。这将返回一个异常的原因。
#include <iostream>
#include <Windows.h>
#include <exception>
using namespace std;
// 服务器开发中通常使用的异常继承体系
class Exception
{
public:
Exception(const string& errmsg, int id)
:_errmsg(errmsg)
, _id(id)
{}
virtual string what() const
{
return _errmsg;
}
protected:
string _errmsg;
int _id;
};
class SqlException : public Exception
{
public:
SqlException(const string& errmsg, int id, const string& sql)
:Exception(errmsg, id)
, _sql(sql)
{}
virtual string what() const
{
string str = "SqlException:";
str += _errmsg;
str += "->";
str += _sql;
return str;
}
private:
const string _sql;
};
class CacheException : public Exception
{
public:
CacheException(const string& errmsg, int id)
:Exception(errmsg, id)
{}
virtual string what() const
{
string str = "CacheException:";
str += _errmsg;
return str;
}
};
class HttpServerException : public Exception
{
public:
HttpServerException(const string& errmsg, int id, const string& type)
:Exception(errmsg, id)
, _type(type)
{}
virtual string what() const
{
string str = "HttpServerException:";
str += _type;
str += ":";
str += _errmsg;
return str;
}
private:
const string _type;
};
void SQLMgr()
{
srand(time(0));
if (rand() % 7 == 0)
{
throw SqlException("权限不足", 100, "select * from name = '张三'");
}
//throw "xxxxxx";
}
void CacheMgr()
{
srand(time(0));
if (rand() % 5 == 0)
{
throw CacheException("权限不足", 100);
}
else if (rand() % 6 == 0)
{
throw CacheException("数据不存在", 101);
}
SQLMgr();
}
void HttpServer()
{
// ...
srand(time(0));
if (rand() % 3 == 0)
{
throw HttpServerException("请求资源不存在", 100, "get");
}
else if (rand() % 4 == 0)
{
throw HttpServerException("权限不足", 101, "post");
}
CacheMgr();
}
int main()
{
while (1)
{
try
{
HttpServer();
}
catch (const Exception& e) // 这里捕获父类对象就可以
{
// 多态
cout << e.what() << endl;
Sleep(1000);
}
catch (...)
{
cout << "Unkown Exception" << endl;
}
}
return 0;
}原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。