今晚看了一下C++ primer 的异常处理的简单介绍,在这里简略记一下
异常处理机制包括异常检测和异常处理
在C++中异常处理主要包括
throw表达式 : 用 throw 表达式来抛出(引发)异常 (那自然有接收)
try语句块(包含catch子句) :用try语句块来表示这段代码可能会抛出异常,抛出的异常通常会被某个 catch 子句处理
一套异常类(用来传递异常具体信息) exception runtime_error
try语句块的通用语法形式
try() {
} catch() {
} catch(){
}
如果抛出的异常没有匹配的catch语句处理,会调用 terminate 函数 让程序非正常退出
写的一个样例(被除数为 0)
#include<iostream>
#include<cstring>
#include<exception>
#include<stdexcept>
using namespace std;
void fun()
{
int temp1,temp2;
while(cin >> temp1 >> temp2)
{
try {
if(temp2 == 0) throw runtime_error("除数不能为0");
cout << temp1 / temp2 << endl;
}
catch(runtime_error err) {
cout << err.what() << "\n是否重新输入?输入'y'或者'n'" << endl;
char c;
cin >> c;
if(c == 'n' || !cin) break;
}
}
}
///terminate
int main()
{
fun();
}