在C++中引发NullPointerException
Throwing a NullPointerException in C++
本文关键字:NullPointerException C++ 更新时间:2023-10-16
在对nullptr对象调用方法时,是否可以让C++抛出NPE,而不是进行未定义的行为?我可以为SEGFAULT信号创建一个处理程序,但这确实很危险,因为并不是每个SEGFAUULT都是NullPointerException。如果我必须通过检查If子句来做到这一点,有有效的方法吗?也许也在圣诞节?
是的,你可以,但这不是一个好主意(无论如何,你都不应该处理指针,在现代C++中,指针被保存在管理其寿命的对象中)。
您可以始终定义一个包含指针的类。然后,当您尝试使用operator->()
时,如果持有的指针是nullptr
,它就会抛出。
template<typename T>
class ThrowingUniquePtr
{
T* ptr;
public:
// STUFF to create and hold pointer.
T* operator->()
{
if (ptr) {
return ptr;
}
throw NullPointerException; // You have defined this somewhere else.
}
};
class Run
{
public:
void run() {std::cout << "Runningn";}
};
int main()
{
ThrowingUniquePtr<Run> x(new Run);
x->run(); // will call run.
ThrowingUniquePtr<Run> y(nullptr);
y->run(); // will throw.
}
另一种异常处理方式:使用NULL指针调用函数
#include <iostream>
#include <typeinfo>
using namespace std;
char str_NullPointer[25] = "NULL Pointer exception";
char str_Arithmetic[25] = "Arithmetic exception";
class A
{
public:
int i = 20;
public:
int function()
{
printf("Function startn");
try
{
if (this)
{
printf("value of i = %d n", i);
}
else
{
throw str_NullPointer; /* Exception thrown in Case 2 */
}
}
catch(const int s)
{
printf("%dn", s);
}
catch(const char* s)
{
printf("%s in %sn", s, typeid(this).name()); /* Exception and Class Name */
}
printf("Function endnnn");
}
};
int main() {
//code
printf("Case 1: With Pointern");
A *obj = new A();
obj->i = 20;
obj->function();
printf("Case 2: With NULL Pointern");
delete obj;
obj = NULL;
obj->function();
return 0;
}
输出:
Case 1: With Pointer
Function start
value of i = 20
Function end
Case 2: With NULL Pointer
Function start
NULL Pointer exception in P4abcd
Function end
相关文章:
- 没有找到相关文章