我是 GTest 框架的新手。我想通过我的一个测试来实现异常处理。我实现了一个简单的队列数据结构,配备了在队列中查找值的功能。函数的实现和调用如下。
队列.cpp
LinkedListNode *CustomDataTypes::Queue::find_value(int value)
{
auto found = false;
auto current_node = head;
try
{
if(current_node == nullptr){
throw new std::runtime_error("Queue is empty");
}
// Sequentially check each node
while (!found){
// Compare value
if(current_node->value == value){
found = true;
}else{
if(current_node->next != nullptr)
{
// If not, then move on to the next node
auto next_node = current_node->next;
current_node = next_node;
}else{
throw new std::runtime_error("Value does not exist in Queue");
}
}
}
}
catch(const std::runtime_error& e)
{
std::cerr << "\n ERROR: " << e.what() << "\n\n";
}
// If correct, then return address of the node
return current_node;
}
main.cpp
// GIVEN: Queue class is filled with 3 elements
auto new_queue = Queue();
new_queue.push_back(1);
new_queue.push_back(2);
new_queue.push_back(3);
.
.
// WHEN: Startup
// THEN: Attempts to find non-existing element in queue
EXPECT_THROW(new_queue.find_value(4), std::runtime_error);
问题
Expected: new_queue.find_value(4) throws an exception of type std::runtime_error.
Actual: it throws a different type.
问题
try
和catch
语句应该在哪里?在 TEST
或 queue.cpp
范围内?任何提示或建议将不胜感激:)
总结评论中的讨论:
在 C++ 中,您应该在不使用
new
关键字的情况下引发异常。首先将 throw new std::runtime_error("Value does not exist in Queue");
替换为 throw std::runtime_error("Value does not exist in Queue");
正如 @Yksisarvinen 所指出的,尝试在抛出的同一块中捕获异常是没有意义的。要么抛出异常并在调用者的代码中处理它,要么在发生此错误时使用默认行为并且根本不抛出。
因此,通过从函数 find_value 中删除 try-catch 块并在没有
new
的情况下抛出,您的测试将会通过。