首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++中的异常类不起作用

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

Stack Overflow用户
提问于 2019-02-11 13:41:58
回答 1查看 378关注 0票数 0

我是一个在学习C的过程中的学生,我正在尝试做一个用户定义的异常类。我看了几段视频,读了几本教程,最后得到了这个节目。然而,每次我试图运行程序并抛出异常时,程序就会关闭,并且我会得到包含更改某些设置的选项的休闲消息。

EC1.exe中0x75BF1812处的未处理异常: Microsoft C++异常:内存位置为0x0073F4BC的FileNotFound。已发生

我试着去查这条消息,但什么也没找到。任何关于如何前进或我做错了什么的建议都将不胜感激。

代码语言:javascript
复制
#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;
    }
}
EN

回答 1

Stack Overflow用户

发布于 2019-02-11 13:44:35

std::exception::what具有以下签名:

代码语言:javascript
复制
virtual const char* what() const noexcept;

您忽略了const限定符:您没有覆盖它。它应该是:

代码语言:javascript
复制
struct FileNotFound : std::exception
{
    const char* what() const noexcept override
    {
        return "Exception: File not found.\n";
    }
};

但是不能解决您的问题:您没有捕捉到异常。如果在main中抛出一个未处理的异常(包括堆栈展开之类的其他情况),则调用abort(),您的系统可能会像您的系统一样打印一条助手消息。你需要记录自己在C++中的异常

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54631880

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档