我是一个在学习C的过程中的学生,我正在尝试做一个用户定义的异常类。我看了几段视频,读了几本教程,最后得到了这个节目。然而,每次我试图运行程序并抛出异常时,程序就会关闭,并且我会得到包含更改某些设置的选项的休闲消息。
EC1.exe中0x75BF1812处的未处理异常: Microsoft C++异常:内存位置为0x0073F4BC的FileNotFound。已发生
我试着去查这条消息,但什么也没找到。任何关于如何前进或我做错了什么的建议都将不胜感激。
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
class FileNotFound : public std::exception
{
public:
const char* what()
{
return ("Exception: File not found.\n");
}
};
const int NO_OF_COMPUTES = 2;
struct computerType
{
std::string cID;
std::string manufacturer;
std::string name;
std::string cpuSpeed;
int ramSize;
double price;
};
void getComputer(std::ifstream& infile);
/*void writeComputer(ofstream& outfile, computerType list[],
int listSize);*/
int main()
{
std::ifstream infile; //input file stream variable
std::ofstream outfile; //output file stream variable
std::string inputFile; //variable to hold the input file name
std::string outputFile; //variable to hold the output file name
computerType computerTypeList[NO_OF_COMPUTES];
std::cout << "Enter the input file name: ";
std::cin >> inputFile;
std::cout << std::endl;
infile.open(inputFile.c_str());
if (!infile)
{
FileNotFound a;
throw a;
}
getComputer(infile);
infile.close();
outfile.close();
system("pause");
return 0;
}
void getComputer(std::ifstream& infile)
{
int index;
std::string cID;
std::string manufacturer;
std::string name;
std::string cpuSpeed;
int ramSize;
double price;
infile >> cID;
while (infile)
{
infile >> manufacturer >> name >> cpuSpeed >> price;
std::cout << cID << " " << manufacturer << " " << name << " " << cpuSpeed << " " << price;
infile >> cID;
}
}发布于 2019-02-11 13:44:35
std::exception::what具有以下签名:
virtual const char* what() const noexcept;您忽略了const限定符:您没有覆盖它。它应该是:
struct FileNotFound : std::exception
{
const char* what() const noexcept override
{
return "Exception: File not found.\n";
}
};但是不能解决您的问题:您没有捕捉到异常。如果在main中抛出一个未处理的异常(包括堆栈展开之类的其他情况),则调用abort(),您的系统可能会像您的系统一样打印一条助手消息。你需要记录自己在C++中的异常。
https://stackoverflow.com/questions/54631880
复制相似问题