C++ 抛出新owneExceptionClass让程序崩溃

C++ 抛出新owneExceptionClass让程序崩溃,c++,class,exception,unhandled,C++,Class,Exception,Unhandled,我有一个具有以下代码的函数: if (!File::exists(i_filename)) throw new FileNotFoundException(i_filename); 我的FileNotFoundException如下所示 h < VisualStudio告诉我未处理的异常,在2xGAME.EXE中0x722-D8A8:微软C++异常:存储位置0x00 18F5FC文件FieloToFunExtExc} < /Cord> 当我运行时抛出新的FileNotFoundExceptio

我有一个具有以下代码的函数:

if (!File::exists(i_filename)) throw new FileNotFoundException(i_filename);
我的FileNotFoundException如下所示 h

< VisualStudio告诉我<代码>未处理的异常,在2xGAME.EXE中0x722-D8A8:微软C++异常:存储位置0x00 18F5FC文件FieloToFunExtExc} < /Cord> 当我运行
时抛出新的FileNotFoundException(I\u文件名)


有人知道怎么了吗?很抱歉,我以前从未创建过异常类。

如注释所示,您需要一个try-catch块来捕获异常。否则,当抛出异常时,您将无法告诉编译器应该发生什么

btw,在C++中抛出指针是个坏主意,因为catch块中的类型匹配可能不如预期。而是抛出一个值并捕获对它的引用:

if (!File::exists(i_filename))
    throw FileNotFountException{i_filename};

// .... somewhere else

try {
  // call the above function
} catch(FileNotFountException& e) {
  // handle the exception here
}
除了您的实际问题之外:最好选择初始化列表而不是在构造函数中赋值:

class FileNotFountException : public std::exception {
    public:
        FileNotFountException(const std::string &i_filename): 
            m_filename{i_filename} {};
    private:
        std::string m_filename;
};
这将使用
i\u filename
的副本初始化
m\u filename
,而您的实现将使用空字符串初始化
m\u filename
,然后复制
i\u filename
的内容


如果您的构造函数很简单,您应该更愿意将定义直接放在头文件中的声明中。它将像一个声明为
inline

的函数一样编译,您正在使用的try-catch块在哪里?是。如果抛出异常,它必须在某个地方被捕获。否则你会得到你得到的,嗯?你认为抛出异常到底有什么作用?@user387443你可能想了解异常是什么,顺便说一下,不要动态分配异常。这不是Java。只要写
throw FileNotFoundException()
(更正拼写后!)好吧,慢慢地,但我肯定知道如何使用异常。。在捕手区该怎么办?你写了“在这里处理异常”,但我会在异常类中做所有的事情。不,那不是一个好地方。如果一个异常永远不会发生,编译器可能会采取一些捷径,排除您的假设。当它能够证明它在任何情况下都不会被cought时,它甚至可能会删除调用异常类的构造函数的代码。就这样使用它们吧,它们是用来使用的,你不会有意外。好的,谢谢。我会仔细看看例外情况。
if (!File::exists(i_filename))
    throw FileNotFountException{i_filename};

// .... somewhere else

try {
  // call the above function
} catch(FileNotFountException& e) {
  // handle the exception here
}
class FileNotFountException : public std::exception {
    public:
        FileNotFountException(const std::string &i_filename): 
            m_filename{i_filename} {};
    private:
        std::string m_filename;
};