一、介绍
基本内容:
- C++ 异常处理机制会涉及 try、catch、throw 三个关键字(注意没有 finally 关键字)
- 程序的错误大致可以分为三种,分别是语法错误、逻辑错误和运行时错误:C++ 异常(Exception)机制就是为解决运行时错误而引入的。
- C++ 规定,异常类型可以是 int、char、float、bool 等基本类型,也可以是指针、数组、字符串、结构体、类等聚合类型。
- C++ 语言本身以及标准库中的函数抛出的异常,都是 exception 类或其子类的异常。(规则和格式)
C++ 异常处理的流程,具体为:抛出(Throw)–> 检测(Try) --> 捕获(Catch)
异常必须显式地抛出,才能被检测和捕获到;如果没有显式的抛出,即使有异常也检测不到。
二、示例
#include <iostream>
#include <exception>
#include <thread>
using namespace std;
//自定义异常类
class CStudentExc
{
public:
CStudentExc(): m_flag(1){
};
CStudentExc(int num): m_flag(num){
}
void what() const
{
if(1 == m_flag)
{
cout<<"Error: m_flag is 1."<<endl;
}
else if(2 == m_flag)
{
cout<<"Error: m_flag is 2."<<endl;
}
else
{
cout<<"Error: m_flag is " << m_flag <<endl;
}
}
private:
int m_flag;//不同的错误类型
};
int test_throw(const int type)
{
switch(type)
{
case 1:
throw 1;
break;
case 2:
throw 2.2;
break;
case 3:
throw "string 3";
break;
case 4:
throw CStudentExc();
break;
case 5:
throw CStudentExc(2);
break;
case 6:
throw CStudentExc(3);
break;
}
std::cout<< "test_throw end"<< std::endl;
return 0;
}
int test_try_catch(const int type)
{
try{
test_throw(type);
}
catch(int &e)
{
std::cout<< "int :"<< e << std::endl;
}
catch(float &e)
{
std::cout<< "float :"<< e << std::endl;
}
catch(double &e)
{
std::cout<< "double :"<< e << std::endl;
}
catch(std::string &e)
{
std::cout<< "std::string :"<< e << std::endl;
}
catch(const char *e)
{
std::cout<< "const char * :"<< e << std::endl;
}
catch(const CStudentExc &e)
{
e.what();
}
catch(std::exception &e)
{
std::cout<< "std::exception :"<< e.what() << std::endl;
}
return 0;
}
int main(int argc, char **argv)
{
test_try_catch(1); //throw int
test_try_catch(2); //throw float 实际是double
test_try_catch(3); //throw string
test_try_catch(4); //
test_try_catch(5); //
test_try_catch(6); //
test_try_catch(100); //exit
return 0;
}
输出
int :1
double :2.2
const char * :string 3
Error: m_flag is 1.
Error: m_flag is 2.
Error: m_flag is 3
test_throw end