卓姆比尼人免安装绿色版
637M · 2025-09-26
传统C语言处理错误的方式:
程序的异常检测部分使用throw表达式引发一个异常。throw表达式包含关键字throw和紧随其后的一个表达式,其中表达式的类型就是抛出的异常类型。
catch子句包括三部分:关键字catch、括号内一个(可能未命名的)对象的声明(称作异常声明,exception declaration)以及一个块。当选中某个catch子句处理异常之后,执行与之对应的块。catch一旦完成,程序跳转到try语句块最后一个catch子句之后的那条语句继续执行。
C++标准库定义了一组类,用于报告标准库函数遇到的问题。这些异常类也可以在用户编写的程序中使用,它们分别在4个文件头中:
异常类型只定义了一个名为what的成员函数,该函数没有任何参数,返回值是一个指向C风格的字符串的const char*。该字符串的目的是提供关于异常的一些文本信息。
异常的抛出和匹配原则:
在函数调用链中异常栈展开匹配原则:
#include <iostream>
#include <stdexcept>
double Division(int a, int b)
{
//当 b == 0时抛出异常
if (b == 0)
{
throw "Division by zero condition!";
}
else
{
return ((double)a / (double)b);
}
}
void Func()
{
int len, time;
std::cin >> len >> time;
std::cout << Division(len, time) << std::endl;
}
int main()
{
try
{
Func();
}
catch (const char* errmsg)
{
std::cout << errmsg << std::endl;
}
catch (...)
{
std::cout << "unkown exception" << std::endl;
}
return 0;
}
键盘输入10和0,分别表示a和b,所得结果:
double Division(int a, int b)
{
//当b==0时抛出异常
if (b == 0)
{
throw "Division by zero conditon!";
}
return (double)a / (double)b;
}
void Func()
{
int* array = new int[10];
try
{
int len, time;
std::cin >> len >> time;
std::cout << Division(len, time) << std::endl;
}
catch (...)
{
std::cout << "delete []" << array << std::endl;
delete[] array;
throw;
}
std::cout << "delete[]" << array << std::endl;
delete[] array;
}
int main()
{
try
{
Func();
}
catch (const char* errmsg)
{
std::cout << errmsg << std::endl;
}
return 0;
}
void func() throw(A,B,C,D);//func函数会抛出A/B/C/D中的某种类型的异常
void* operator new(std::size_t size) throw(std::bad_alloc);//这个函数只会抛出bad_alloc的异常
void* operator delete(std::size_t size ,void* ptr)throw();//表示这个函数不会抛出异常
shared_ptr()noexcept;//C++11新增noexcept,表示不会抛出异常
下面展示一段服务器开发过程中常用的异常继承体系:
#include <iostream>
#include <stdexcept>
#include <string>
#include <thread>
class Exception {
public:
Exception(int errid,const const std::string& msg)
:_errid(errid)
,_errmsg(msg)
{ }
const std::string& GetMsg()const
{
return _errmsg;
}
int GetErrid()const
{
return _errid;
}
virtual std::string what()const
{
return _errmsg;
}
protected:
int _errid;//error code
std::string _errmsg;//error description
};
class sqlException : public Exception
{
public:
sqlException(int errid, const std::string& msg, const std::string& sql)
:Exception(errid, msg)
,_sql(sql)
{ }
virtual std::string what()const
{
std::string str = "sqlException: ";
str += _errmsg;
str += "->";
str += _sql;
return str;
}
private:
const std::string _sql;
};
class cacheException :public Exception
{
public:
cacheException(int errid,const std::string& errmsg)
:Exception(errid,errmsg)
{ }
virtual std::string what()const
{
std::string str = "cacheException:";
str += _errmsg;
return str;
}
};
class httpServerException :public Exception
{
public:
httpServerException(int errid,const std::string& errmsg,const std::string& type)
:Exception(errid,errmsg)
,_type(type)
{ }
virtual std::string what()const
{
std::string str = "httpServerException:";
str += _type;
str += ":";
str += _errmsg;
return str;
}
private:
const std::string _type;
};
void SQLMgr()
{
srand(time(0));
if (rand() % 7 == 0)
{
throw sqlException(100,"权限不足", "select* from name = '张飞'");
}
}
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 (true)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
try
{
HttpServer();
}
catch (const Exception& e)
{
//多态
std::cout << e.what() << std::endl;
}
catch (...)
{
std::cout << "unkown exception" << std::endl;
}
}
return 0;
}
C++提供了一系列标准的异常,定义在exception
中,我们可以在程序中使用这些标准异常。它们以父子类层次结构组织起来的,具体如下:
异常 | 描述 |
---|---|
std::exception | 该异常说所有标准C++异常的父类 |
std::bad_alloc | 该异常可以通过new抛出 |
std::bad_cast | 该异常可以通过dynamic_cast抛出 |
std::bad_exception | 这在处理C++程序中无法预期的异常时非常有用 |
std::bad_typeid | 该异常可以通过typeid抛出 |
std::logic_error | 理论上可以通过读取代码来检测到的异常 |
std::domain_error | 当使用一个无效的数学域时,会抛出该异常 |
std::invalid_argument | 当使用了无效的参数时,会抛出该异常 |
std::length_error | 当创建了太长的std::string时,会抛出该异常 |
std::out_of_range | 该异常可以通过方法抛出,例如std::vector和std::bitset<>::operator |
std::runtime_error | 理论上不可以通过读取代码来检测到的异常 |
std::overflow_error | 当发生数学上溢时,会抛出该异常 |
std::range_error | 当尝试存储超出范围的值时,会抛出该异常 |
std::underflow_error | 当发生数学下溢时,会抛出该异常 |
说明:实际中,我们可以去继承exception类实现自己的异常类。但是实际开发过程中,会自定义一套异常继承体系,因为C++标准库设计的异常不够好用。
C++异常的优点
C++异常得缺点
腾讯 QQ 音乐推出“网赚畅听包”会员,付费后每天看广告获取听歌权益
开源电子书管家 Calibre 8.11 发布:整合 AI 问答功能,随时解答你的提问