小古银的官方网站(完整教程):http://www.xiaoguyin.com/
C++入门教程视频:https://www.bilibili.com/video/av20868986/
目录
抛出异常
使用关键字throw
抛出异常。throw
不仅仅是抛出std::exception
和派生类的对象,其实它可以抛出所有的变量和值,例如:throw 23333;
或者throw std::string("小古银嘿嘿嘿");
。
当抛出int
类型的值时,应该捕获int
类型:
#include <iostream>
int main(void)
{
try
{
throw 23333;
}
catch (int e)
{
std::cout << e << std::endl;
}
return 0;
}
当抛出std::string
类型的值时,应该捕获std::string
类型:
#include <iostream>
int main(void)
{
try
{
throw std::string("我是异常");
}
catch (const std::string &e)
{
std::cout << e << std::endl;
}
return 0;
}
上面只是为了讲解如何使用throw
,所以在捕获语句里面直接抛出异常,写代码的时候应该没人会这么玩。