自定义异常怪异行为

Custom exception weird behavior

本文关键字:自定义异常      更新时间:2023-10-16

我创建了一个自定义异常类testException

throw创建一个testException对象,该对象在创建时接收所需的异常名称。

testException被捕获时(通过引用),它应该通过使用成员函数Get.Exception返回异常的名称。

由于某些原因,函数没有被调用,而是得到错误:

在抛出testException实例后终止调用

我在这里看到了一个类似的例子,应该可以工作。

    为什么我得到上述错误?

代码:

Exception.h

#include <iostream>
#include <string>
#ifndef TESTEXCEPTION_H
#define TESTEXCEPTION_H
using std::cout;
using std::cin;
using std::endl;
using std::string;
class testException {
public:
    testException(string);
    string GetException();
    ~testException();
protected:
private:
    string myexception;
};
#endif // TESTEXCEPTION_H

Exception.cpp

#include "testException.h"
testException::testException(string temp) : myexception(temp) {
    // ctor
}
string testException::GetException() {
    return myexception;
}
testException::~testException() {
    // dtor
}

main.h

#include <iostream>
#include "testException.h"
using std::cout;
using std::cin;
using std::endl;
int main() {
    throw testException ("Test");
    try {
        // Shouldn't be printed if exception is caught:
        cout << "Hello World" << endl;
    } catch (testException& first) {
        std::cerr << first.GetException();
    }
    return 0;
}

您正在抛出try块之外的异常。

int main() {
    throw testException("Test"); // Thrown in main function scope.
                                  // Will result in call to terminate.
    try {
        /* ... */
    } catch (testException& first) {
        // Only catches exceptions thrown in associated 'try' block.
        std::cerr << first.GetException();
    }
    /* ... */
}

异常只能在try-catch子句内部抛出时被捕获。在main函数范围内抛出异常将导致对terminate的调用。

try块将"尝试"执行其中的所有内容,如果在此过程中抛出任何异常,如果相关的异常处理程序接受的参数类型与所抛出的异常可隐式转换的类型相同,则将捕获这些异常。

一旦抛出异常,try块内剩余的语句将被跳过,所有具有自动存储持续时间的对象将被销毁,异常将被相应地处理。

将throw语句移动到try-catch子句

的实例

将抛线:throw testException ("Test");移至try {} catch(catch (testException& first) {}块。