The following program throws nullptr
and then catches the exception as int*
:
#include <iostream>
int main() {
try {
throw nullptr;
}
catch(int*) {
std::cout << "caught int*";
}
catch(...) {
std::cout << "caught other";
}
}
In Clang and GCC the program successfully prints caught int*
, demo: https://gcc.godbolt.org/z/789639qbb
However in Visual Studio 16.11.2 the program prints caught other
. Is it a bug in MSVC?
The nullptr keyword represents a null pointer value. Use a null pointer value to indicate that an object handle, interior pointer, or native pointer type does not point to an object. Use nullptr with either managed or native code.
There's no such thing as "null pointer exception" in C++. The only exceptions you can catch, is the exceptions explicitly thrown by throw expressions (plus, as Pavel noted, some standard C++ exceptions thrown intrinsically by standard operator new , dynamic_cast etc). There are no other exceptions in C++.
It's just the string and the character array parameters that cause ambiguity as character arrays and objects can happily coexist. The char array null cannot be printed by the PrintStream since it causes a NullPointerException .
It is non-zero, it's true. A null pointer is zero, and so evaluates to false.
Null Pointer Exception In Java. NullPointerException is a RuntimeException. In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when program attempts to use an object reference that has the null value. These can be: Invoking a method from a null object.
Thank you. The nullptr keyword specifies a null pointer constant of type std::nullptr_t, which is convertible to any raw pointer type. Although you can use the keyword nullptr without including any headers, if your code uses the type std::nullptr_t, then you must define it by including the header <cstddef>.
Avoid using NULL or zero ( 0) as a null pointer constant; nullptr is less vulnerable to misuse and works better in most situations. For example, given func (std::pair<const char *, double>), then calling func (std::make_pair (NULL, 3.14)) causes a compiler error.
Similar conversions exist for any null pointer constant, which includes values of type std::nullptr_t as well as the macro NULL . Demonstrates that nullptr retains the meaning of null pointer constant even if it is no longer a literal.
Looks like a bug in Visual Studio, according to the standard [except.handle]:
A handler is a match for an exception object of type
E
if[...]
- the handler is of type
cv T
orconst T&
whereT
is apointer
orpointer-to->member
type andE
isstd::nullptr_t
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With