and*_*rey 0 c++ exception-handling
我试图抓住指针异常.我的代码看起来像这样.我得到"未处理的例外".我做错了什么?任何帮助将不胜感激.
#include <iostream>
#include <exception>
using namespace std;
struct Node{
int data;
Node* next;
};
int list_length(struct Node* head){
try{
int i = 0;
while (head->next){
head = head->next;
i++;
}
return i + 1;
}
catch (exception& e){
cout << e.what() << endl;
}
};
int main(void){
struct Node *perr = nullptr;
list_length(perr);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这里没有C++例外.您只需取消引用空指针,即未定义的行为,而不是异常.您应该head在取消引用之前检查,这不是nullptr.可能,你正在使用Windows和Windows异常被抛出.你可以在这里阅读:如何捕获空指针异常?