双向链表异常处理无法触发错误?求实现内存不足、空表删除等异常抛出
双向链表异常捕获的实现与触发技巧
一、触发「从空链表删除元素」异常
你当前代码没有删除节点的逻辑,自然碰不到这类异常。要触发它,得先实现删除函数,并且在操作前检查链表状态:
先写一个删除尾部节点的函数:
void deleteTail(Node*& head, Node*& tail) { // 空链表直接抛出异常 if (head == nullptr) { throw runtime_error("尝试从空链表删除元素"); } // 处理链表只有一个节点的情况 if (head == tail) { delete tail; head = tail = nullptr; } else { Node* temp = tail; tail = tail->prev; tail->next = nullptr; delete temp; } }
然后在main函数里测试空链表删除:
int main() { // 注意:C++标准要求main函数必须返回int,不能用void Node* head = nullptr; Node* tail = nullptr; try { deleteTail(head, tail); // 空链表调用删除操作,直接触发异常 } catch (const runtime_error& e) { cout << "捕获异常:" << e.what() << endl; } // ... 其他代码 return 0; }
二、触发「内存不足」异常
默认情况下,new关键字在内存耗尽时会抛出bad_alloc异常,但现代系统内存充足,很难自然触发。可以用两种方式模拟:
1. 手动抛出异常用于测试
写一个创建节点的函数,主动抛出bad_alloc异常:
Node* createNode(int data) { // 模拟内存不足,注释此行即可恢复正常节点创建逻辑 throw bad_alloc(); Node* node = new Node(); node->data = data; node->next = node->prev = nullptr; return node; }
调用时就能捕获异常:
try { Node* node = createNode(4); } catch (const bad_alloc& e) { cout << "捕获内存不足异常:" << e.what() << endl; }
2. 系统层面限制进程内存
比如在Linux系统下,用ulimit -v 1024命令限制进程只能使用1MB内存,然后循环创建节点直到耗尽内存,就能触发new的原生bad_alloc异常。
三、你当前代码的问题
你现有的try-catch块完全不会生效,原因有两个:
- 抛出的是整数
2,但捕获的是exception类型,类型不匹配,所以无法进入catch分支 main函数返回类型用void不符合C++标准,必须改成int
修改后的try-catch示例:
try { if (tail != head) { throw runtime_error("链表节点数大于1"); // 抛出标准异常类型 } } catch (const exception& x) { // 用引用捕获,避免不必要的对象拷贝 cout << "捕获异常:" << x.what() << endl; }
四、完整可运行示例代码
#include <iostream> #include <stdexcept> // 必须包含此头文件才能使用标准异常类 using namespace std; struct Node { int data; Node* next; Node* prev; }; void printFront(Node* head) { Node* curr = head; while (curr != nullptr) { cout << curr->data << " "; curr = curr->next; } cout << endl; } void deleteTail(Node*& head, Node*& tail) { if (head == nullptr) { throw runtime_error("尝试从空链表删除元素"); } if (head == tail) { delete tail; head = tail = nullptr; } else { Node* temp = tail; tail = tail->prev; tail->next = nullptr; delete temp; } } Node* createNode(int data) { // 模拟内存不足,注释此行恢复正常创建逻辑 throw bad_alloc(); Node* node = new Node(); node->data = data; node->next = node->prev = nullptr; return node; } int main() { // 测试空链表删除异常 Node* head = nullptr; Node* tail = nullptr; try { deleteTail(head, tail); } catch (const runtime_error& e) { cout << "异常1:" << e.what() << endl; } // 测试内存不足异常 try { Node* node = createNode(4); } catch (const bad_alloc& e) { cout << "异常2:" << e.what() << endl; } // 正常创建链表测试 head = tail = new Node(); head->data = 4; head->next = head->prev = nullptr; try { if (tail != head) { throw runtime_error("链表节点数大于1"); } else { cout << "链表当前只有一个节点" << endl; } } catch (const exception& e) { cout << "异常3:" << e.what() << endl; } printFront(head); return 0; }
内容的提问来源于stack exchange,提问作者Larrythelobster
相关产品推荐
相关产品推荐

