c++异常
1.1 使用throw抛出异常,异常只会被抓住一次,并且抛出异常后的程序不会被执行。
#include <iostream>
using namespace std;
void fun1()
{
throw 1;
cout<<"test"<<endl;
}
void fun2()
{
try
{
fun1();
}
catch(int e)
{
cout<<"exception is catched "<<e<<endl;
}
}
int main()
{
try
{
fun2();
}
catch(int e)
{
cout<<"test2"<<endl;
}
}
1.2 输出结果
exception is catched 1
2.1 捕获运行期异常
#include <iostream>
#include <stdexcept>
using namespace std;
void fun()
{
throw runtime_error("Invalid input");
}
int main()
{
try
{
fun();
}
catch(runtime_error& e)
{
cout<<e.what()<<endl;
}
}
2.2 输出结果
Invalid input