如果程序抛出的异常没有捕获,程序结束。可以对main()函数使用try/catch结构,以捕获所有未经处理的异常,如下所示:
try{
main(argc,argv);
}catch(...){
//
}
这一行为通常并非我们希望的。异常的要点在于给程序一个机会,来处理和修正不希望看到的或不曾预期的情况。
即使无法处理特定的异常,也应该编写代码捕获这个异常,并输出恰当的错误信息。
如果存在未捕获的异常,程序的行为也可能发生变化。当程序遇到未捕获的异常时,会调用内建的terminate()函数,这个函数调用<cstdlib>中的abort()来终止程序。可调用set_terminate()函数设置自己的terminate_handler,这个函数采用指向回调函数(即没有参数,也没有返回值)的指针做参数。Terminate()、set_terminate()和terminate_handler都在<exception>头文件中声明。
try{
main(argc,argv);
}catch(...){
If(terminate_handler != nullptr){
}else{
terminater()
}
}
不要为这一特性激动,因为回调函数必须终止程序。错误是无法忽略的,然而可以在推出之前输出一条有益的错误消息。下面的示例中,main()函数没有捕获readInteferFile()抛出的异常,而将terminate_handler设置为在退出之前输出错误信息的回调函数:
// project20161021.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<stdexcept>
#include<vector>
#include<string>
#include<fstream>
using namespace std;
void readIntegerFile(const string& fileName, vector<int> &dest)
{
ifstream istr;
int temp;
istr.open(fileName);
if (istr.fail())
{
throw runtime_error("Unable to open the file");
}
while (istr >> temp)
{
dest.push_back(temp);
}
if (!istr.eof()) {
//We did not reach the end-of-file
//This means that some error occurred while reading the file
//Throw an exception
//文件结尾是非数字 则抛出
throw runtime_error("Error reading the file.");
}
}
void myTerminate()
{
cout << "Uncaught exception!" << endl;
exit(1);
}
int main()
{
vector<int> myInts;
const string fileName = "C:/Users/Administrator/Desktop/IntegerFile.txt";
set_terminate(myTerminate);
readIntegerFile(fileName,myInts);
for (const auto element : myInts) {
cout << element << " ";
}
cout << endl;
return 0;
}
当设置了新的terminate_handler时,set_terminate()会返回旧的terminate_handler,但是在本示例中并没有显示这一点。Terminate_handler应用于整个程序,因此需要新terminate_handler的代码结束后,最好重新设置旧的terminate_handler。上面的示例中,整个程序都需要新的terminate_handler,因此不需要重新设置。