项目场景:
提示:这是很久很久以前(2007年上学时)学习C++是记录的一个异常错误记录
测试环境:VC 6.0 [已打Sp6补丁]
问题描述:
程序编译和运行都正常,但是在故意输入字母让它出现异常的时候第一次可以捕捉到并且处理了, 第二次再输入字面引发异常的时候就会弹出一个错误提示!
"Debug error"
"abnormal program termination."
代码如下:
//
///头文件:Exception.h---定义类CTest
#ifndef EXCEPTION_H_
#define EXCEPTION_H_
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
class CTest
{
public:
enum
{
ArrSize = 10
}; //利用枚举为数组设置一个长度值
int *pIntArray; /*定义一个整型指针,将用来指向new分配的整型数组*/
CTest(); //构造函数原型
~CTest(); //析构函数原型
void Input() throw(char *); //输入成员函数原型
void Output(); //输出成员函数原型
};
#endif
//
/源文件:Exception.cpp---类CTest的实现文件
#include "Exception.h"
CTest::CTest()
{
pIntArray = new int[ArrSize]; /*用new动态创建一个整型数组*/
for (int a = 0; a < ArrSize; a++)
{
pIntArray[a] = NULL; /*将每个元素的内容初始化为空*/
}
cout << "++++++++++++I'm the constructor++++++++++++\n";
}
CTest::~CTest()
{
delete[] pIntArray; //删除用new动态分配的内存
cout << "----------I'm the destructor----------\n";
}
void CTest::Input() throw(char *)
{
cout << "Please input " << ArrSize << " integer numbers continuously:\n";
for (int i = 0; i < ArrSize; i++)
{
cout << "Number " << i + 1 << " :";
if (!(cin >> pIntArray[i]))
{ //如果输入了非法字符出错之后,抛出异常
cin.clear(); //清除错误输入流特征,如果没有这两句第一次异常就无法捕获
cin.ignore(); //丢弃上次回车符以前的所有输入
throw "illegal input!Please try again:\n"; //抛出异常
}
}
cout << "Input complete.\n";
}
void CTest::Output()
{
cout << "-------------------------------------------------.\n";
cout << "The numbers you just input are:\n";
for (int i = 0; i < ArrSize; i++)
{
cout << pIntArray[i] << "\t";
}
cout << "-------------------------------------------------.\n";
}
//测试主源文件main.cpp
#include "Exception.h"
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
CTest t;
char quit;
do
{
try
{
t.Input();
t.Output();
}
catch (const char *s)
{
cout << s; //输出异常提示信息
t.Input(); //重新提示用户输入数组元素
t.Output(); //如果用户输入完成,打印所有刚才的输入
}
cout << "Do you want to try again? Y/N\n"; //询问用户是否需要重新开始
cin >> quit;
} while (quit != 'n' && quit != 'N');
return 0;
}
原因分析:
第二次输入的函数input是在catch到异常后的异常处理块中了,而不是try块中。所以第二次输入抛出的异常当然是unhandled了...
解决方案:
把catch块里面的
t.Input();//重新提示用户输入数组元素
t.Output();//如果用户输入完成,打印所有刚才的输入
改为 continue就OK了!