C ++中的异常类不起作用

时间:2019-02-11 13:41:59

标签: c++

我是一名学习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;
    }
}

1 个答案:

答案 0 :(得分:3)

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(),并且系统可能会像您一样打印帮助程序消息。您需要document yourself about exceptions in C++