自定义异常怪异行为
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) {}
块。
相关文章:
- C++ 中的自定义异常:在哪里定义它们?
- 我应该C++自定义异常代码放在哪里?
- 自定义异常中的用户定义的空构造函数,具有多个继承和抽象基类
- 处理许多自定义异常的最佳方法是什么
- C++未显示自定义异常消息
- 自定义异常中的消息已损坏
- 为什么要创建自己的自定义异常类
- C++ 构造函数中的自定义异常抛出 ()
- JNI自定义异常具有多个参数
- 如何在抛出未处理的自定义异常后调用 what()?
- 无法创建两个从 std::logic_error 继承的自定义异常类
- 引发异常并直接结束程序的自定义异常处理
- 在C++中创建自定义异常
- G++ 自定义异常处理程序
- 自定义异常并不总是执行 what()
- 从boost::exception和std::runtime_error继承自定义异常类
- 添加到方法的 C++ 自定义异常会出错
- 在自定义异常中仍可访问(误报?
- 自定义异常类 C++
- 未捕获从std::异常派生的C++自定义异常