C ++ exception for null pointers

I have a small function (in a DLL) that looks like this:

int my_function(const char* const s)
{
    try {
        return my_object->do_something_with(s);
    } catch (exception& e) {
        return ERROR_CODE;
    }
}

I thought the try-catch block would prevent anything that could happen internally my_objectfrom propagation to external. Unfortunately, I was wrong, and my program, which calls this function (from VB), just stopped working because I passed the null pointer argument.

So why does my try-catch block not work like (I)? Is there a workaround? I often programmed in Java, and I think it would work there ...

+5
source share
6 answers

Java, Java a NullPointerException. ++ , .

, ++ . ; std::exception. ( , - class NullPointerException {};, std::exception, .)

+9

++ - undefined. , ++ , . - , . , , .

, undefined , ( ). . , , , , , , . :

int my_function(const char* const s)
{
    if (s == 0) return ERROR_CODE;
    return my_object->do_something_with(s);
}

, , do_something_with, . ++ , .

(s==0) - - (s==NULL) (NULL==s) (!s). , .

, , , , , . , , , - , , , , .

++, catch, Windows SEH, .

+5

++ , - std::exception, , ( std?).

, , catch-all, catch (...). , , . , .

, , . Windows Visual Studio, , /EHa, .

+2

++ faq , , ++.

Java , , , , - ( - NULL?)

+1

++ NullPointerException. , (, SIGSEGFAULT).

0

, 1999 ++. STL ++, , , . , .

++ Java. , , ( ).

Java - -, JVM. JVM (), , , , java.lang.NullPointerException.

JVM , JVM SEGFAULT - , de-referencing ( C ++, Pascal, Ada, Assembly BASIC, PEEK/POKE .)

( , ) ++ ( , ) , ( , ) . , true, . . ( , , ) .

Java

if( myPossiblyBadReference == null )
{
   throw java.lang.NullPointerException( "you suck!" );
  // or throw my.own.NPEException(); // preferably a specialization of NullPointerException
}
else
{
   doYourThingieWith( myPossiblyBadReference );
}

- ++, , ++ 0x ( ). , , , ++.

In other words, there is much more elbow lubrication involved in getting these things. Remember that you are working at a lower level of abstraction from the one provided by the JVM.

The JVM is a barrier that gives you many good error handling capabilities (which we typically rely on Java developers). These error handling capabilities should be explicitly encoded when you are working with lower (not only in C ++.)

0
source

All Articles