异常和错误输入的问题!【100求教】
最近在学习C++,编了一个小程序用来测试异常,但是出现了一些奇怪的错误,希望高手指点迷津!
测试环境:VC 6.0 [已打Sp6补丁]
问题说明:程序编译和运行都正常,但是在故意输入字母让它出现异常的时候第一次可以捕捉到并且处理了,
第二次再输入字面引发异常的时候就会弹出一个错误提示!
"Debug error "
"abnormal program termination. "
希望高手帮我看一下是为什么?
我的注释如果不正确还望高手指出来:)
源代码:
//////////////////////////////////////////////////////////
///////头文件:Exception.h---定义类CTest
#ifndef EXCEPTION_H_
#define EXCEPTION_H_
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
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;
}
[解决办法]
呃,C++规定,在catch里再抛异常的话,程序立即崩溃。
要玩异常,还是先认真看点书吧。
比如C++ Primer
[解决办法]
你第二次输入的函数input是在catch到异常后的异常处理块中了,而不是try块中。所以第二次输入抛出的异常当然是unhandled了……