Ramesh
Ramesh

Reputation: 2337

Throwing a value in c++ if it is null

I am trying to check a character pointer is null .How to check if the value is null i am basically from java

char* mypath = getenv("MYPATH");
if(!mypath) //this is not working
   throw "path not found";
if(mypath == NULL) //this is also not working
       throw "path not found";

i am getting an exception "terminate called after throwing an instance of 'char const*'"

Upvotes: 0

Views: 441

Answers (2)

mah
mah

Reputation: 39827

You need to use a try/catch block in order to catch the exception and handle it.

For example:

#include <stdio.h>
int main(void)
{
  try {
    throw "test";
  }
  catch (const char *s) {
    printf("exception: %s\n", s);
  }
  return 0;
}

Please note that throwing a C string as an exception is really not appropriate. See C++ Exceptions - Is throwing c-string as an exception bad? as commented by @Jefffrey for a discussion on that along with alternatives.

Upvotes: 6

James Kanze
James Kanze

Reputation: 153977

The problem isn't the test: both of your if are correct (as far as the compiler is concerned—the second is preferable for reasons of readability). The problem is that you're not catching the exception anywhere. You're throwing a char const[13], which is converted to a char const* as the type of the exception, and you don't have a catch ( char const* ) anywhere in the calling code.

In C++, it's usual (but not at all required) to only throw class types derived from std::exception; about the only exception to this rule is to throw an int for program shutdown, and then only if that is the documented convention in the context where you work. (It only works correctly if main catches int and returns the value.)

Upvotes: 9

Related Questions