《c++程序设计语言(第四版)》2.4.3章节
异常负责报告运行时的错误。
1、标准库异常
#include <stdio.h>
#define debug qDebug()<<
int main(int argc, char *argv[])
{
int x[2]{1,2};
int i = 2;
try
{
if(i >= 2)
{
throw std::out_of_range("数组越界了");
}
else
{
debug x[i];
}
}
catch(const std::out_of_range & exc)
{
debug exc.what() << "行:" << __LINE__ << "文件:" << __FILE__ << endl;
}
debug "hello";
}
2、自定义异常类
#include <stdio.h>
class emptyList :public std::exception
{
public:
emptyList(QString msg):std::exception(),exceptionMsg(msg)
{
}
QString getExceptionMsg() const
{
return this->exceptionMsg;
}
private:
QString exceptionMsg;
};
#define debug qDebug()<<
int main(int argc, char *argv[])
{
QList<int> list;
try
{
if(list.isEmpty())
{
throw emptyList("容器为空");
}
else
{
debug list.size();
}
}
catch(const emptyList & exc)
{
debug exc.getExceptionMsg() << "行:" << __LINE__ << "文件:" << __FILE__ << endl;
}
debug "hello";
}
3、抛出任何符合要求的对象作为异常,实际上只要一个类可以复制和移动,那么就可以抛出。
struct myError
{
QString msg;
};
#define debug qDebug()<<
int main(int argc, char *argv[])
{
try
{
myError e{};
e.msg = "测试";
throw e;
}
catch(const myError & e)
{
debug e.msg;
}
}
如果禁止拷贝和移动就不能抛出:
4、标准库异常层次一图流: