https://www.cnblogs.com/MrYuan/p/4800257.html
try/catch/throw处理异常
来源:https://www.runoob.com/cplusplus/cpp-exceptions-handling.html
处理异常:转移程序控制权
throw:抛出异常
catch:捕获异常
try:try 块中的代码标识将被激活的特定异常。它后面通常跟着一个或多个 catch 块。
//捕获异常,可以指定想要捕获的异常类型
//如果 try 块在不同的情境下会抛出不同的异常,这个时候可以尝试罗列多个 catch 语句,
//用于捕获不同类型的异常。
try{
// 保护代码
}catch( ExceptionName e1 ){
// catch 块
}catch( ExceptionName e2 ){
// catch 块
}catch( ExceptionName eN ){
// catch 块
}
//catch块处理任何类型的异常
try{
//保护代码
}catch(...){
//能处理任何异常的代码
}
//抛出异常
double division(int a, int b){
if( b == 0 )//分母为0抛出异常
throw "Division by zero condition!";
return (a/b);
}
示例:
#include <iostream>
using namespace std;
double division(int a, int b){
if( b == 0 ) //抛出了const char*异常,捕获异常时,必须在catch块中使用const char*
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;
}