定义:顾名思义,抛异常就是将异常抛出,然后进行处理
C++中抛异常的处理:
有3个关键字:throw、try、catch
throw:当程序出现问题是会抛出异常,通过throw实现
try: try块中放着可能抛出异常的代码
catch:用于捕获异常
#include <iostream>
using namespace std;
double division(int a, int b)
{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
int main ()
{
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
}catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}