Throwing a value in c++ if it is null - c++

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*'"

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.)

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.

Related

Try-catch checking multiple objects in try

I am wondering if a code like this will always break and not go ahead after throwing an exception, so the code wont proceed to second temp.dodaj(b).
Avto *a = new Avto("lambo",4);
Avto *b = new Avto("BMW",3);
Avto *c = new Avto("lexus",6);
SeznamAvtov temp;
try {
temp.dodaj(a);
temp.dodaj(b);
temp.dodaj(c); // here the exception will be thrown
temp.dodaj(b);
} catch(PokvarjenAvto &e) {
e.error();
}
temp.pisi();
My second question is, is it ok to throw objects containing data about error or is an exception &e with const char* what() method a must?
Thank you for your answer
I am wondering if a code like this will always break and not go ahead after throwing an exception, so the code wont proceed to second temp.dodaj(b).
Yes, it will behave as you describe.
My second question is, is it ok to throw objects containing data about error or is an exception &e with const char* what() method a must?
No, you can throw any type you want. But it's a common convention that exception types should be derived from std::exception and override the const char* what() function.

C++ - A few questions about throwing exceptions

I've got a few questions about throwing exceptions in C++.
From what I know about them...
An exception can be thrown from within the main() function. Any block of code that can throw an exception in the main() function should be surrounded by try and catch statements as follows
void foo(//args) {
if (...) {
throw "Error reached";
} ...
int main() {
...
try {
//Code that can throw an excpetion
} catch(const char* msg) (
cerr << msg << endl;
}
...
}
In the example above, why is the argument to the catch a const char *. Doesn't C++ allow for strings? Also, is it possible to throw an exception that isn't a const char *, like an int? or a char?
Does throwing an exception in foo, terminate the foo function?
Are there cases where you could put the try and catch statements in the same function as the throw?
Sorry if these are basic questions.
Thanks SO
why is the argument to the catch a const char *
Because you threw string literal which decays to const char*. In short, you catch what you throw.
Doesn't C++ allow for strings?
It does, but to catch string, you need to throw string in first place.
is it possible to throw an exception that isn't a const char *,
You can throw literally anything. It is a good idea to throw special exception classes, like std::exception and derived from it.
Does throwing an exception in foo, terminate the foo function?
Yes, it does.
Are there cases where you could put the try and catch statements in the same function as the throw?
If you want, you can do that. There are not much cases where doing it is a good idea.
It looks like you need to get a good book and read chapter about exceptions. In the meantime this super-FAQ entry might help you/
You can throw an object of any type.
EDIT: (Hopefully I got this right now)
What you have done is throw a C-string, which is of type const char[13] in this case. C-Arrays will decay to pointers to their first element, in this case a pointer of type const char*.
Typically what you want to do is throw a predefined exception object. They can be found in header <stdexcept> and are derived from a base class std::exception. The derived exception classes are for instance std::logic_error, std::range_error, std::bad_alloc etc.
Their constructors take a string as argument, so you can for instance
throw std::logic_error{"Negative values not allowed."};
This message can be accessed in a catch statement like this:
catch(std::exception &e) // capture reference to base class
{
std::cout << e.what() << '\n'; // what() of derived is called, since virtual
}
If an exception is caught, so-called stack unwinding takes place. You can then deal with the error locally, or rethrow the exception. Only when an exception is thrown and never caught, std::terminate() is called an the program aborted.
You can put try/catch statements anywhere. However, remember what the term "exception" actually means. Cases that can easily dealt with using a simple conditional expression if (n < 0) break; or something like that, don't need the exception treatment. Especially if you can realistically expect this kind of unwanted condition to be true often. Then it is not something "exceptional".
If you decide to deal with an error using exceptions and they can not be treated locally, you may put try/catch clauses around the beginning and end of main().
Since you can put several catch statements directly after a try statement, you can then begin to deal with more specific errors, or simply catch anything via catch(...) { //... }.
This is all described in great detail (including pointers on when and when not to use it, in the C++ FAQ.
EDIT: Here's an example that makes use of try/catch statements. However, not an exception object is caught, but an int (errno). Just to show, that you can really throw/catch anything you like. Let process_several_files() be a function somewhere nested in your code:
std::vector<std::string> process_several_files(std::vector<std::string> const& files)
{
std::vector<std::string> contents{};
contents.reserve(files.size()); // files contains file names from user input
for (auto const& file : files)
{
try
{
contents.emplace_back(get_file_contents(file.c_str())); // A "C like" function. get_file_contents() will throw "errno", if a file does not exist
}
catch(int err)
{
std::cerr << "***Error while opening " << file << " : " << std::strerror(err) << "***\n";
continue; // "scope" didn't change, just keep iterating!
}
}
return contents;
}

C++ exception, thow const char* type and catch

I am coding using a very simple exception in C++.
but that is not working as i expect.
and i don't know why even though in debugging mode.
i attach a picture that show variable in eclipse debugging mode at the catch point.
i excepted that the code flow will go into if statement but it go into else statement.
as this problem is too simple, i think that i have misunderstood on handling exception, please fix my understanding.
throw "connection fail";
.
catch(const char* e){
if(e == "connection fail"){
clients.erase(client);
continue;
}else{
std::cout << e << std::endl;
assert(NULL);
}
}
You're lucky that the code didn't work as expected, there's a good chance it might have, and then broken when you rebuilt your code a long time from now.
if(e == "connection fail"){
The problem above is that you're comparing two pointers (that point to two distinct string literals), and not the strings themselves as you expect it to. The reason I said it might've worked is because compilers are allowed to pool string literals, meaning it would've used the same copy of the string literal in both places, and the check would've passed, leading you to believe that the code works correctly. Of course, there's no guarantee that that would always happen, and your code might break silently one day when you recompile.
To actually compare the strings, either use strcmp, or convert one of the operands to std::string.
try {
throw "connection fail";
} catch( char const *e ) {
if(std::string(e) == "connection fail") {
std::cerr << "caught: " << e << std::endl;
}
}
A better solution is to throw types that derive from std::exception instead. I'd change your code to:
try {
throw std::runtime_error("connection fail");
} catch( std::exception const& e ) {
std::cerr << "caught: " << e.what() << std::endl;
}
Please don't throw const char*, that makes no sense!
throw std::runtime_error("My Error");
catch (const std::runtime_error& e)
or create your own exception that contains variables which indicate exception detail, or different object types which indicate the problem! Then you don't need to do any string comparison.
You can't compare C-style strings with ==, you must use strcmp. Most of the time.
The == is only comparing the pointer addresses. In this case you have two strings so they're at different addresses, even though they may contain the same characters in the string.
You can make the == comparison work if you can ensure that both strings are actually the same location in memory. Here's a way to make it work:
static const char * connection_fail = "connection fail";
throw connection_fail;
catch(const char* e){
if(e == connection_fail){
// ...
The better solution all around would be to not throw strings, but throw objects derived from std::exception instead. These contain a what() method that can be used to get a string describing the error.

std::exception using message from local object

Is the following code safely throwing an exception with custom message?
#include <exception>
#include <sstream>
#include <string>
#include <iostream>
int main() {
try {
std::ostringstream msg;
msg << "give me " << 5;
throw std::exception(msg.str().c_str());
} catch (std::exception& e) {
std::cout << "exception: " << e.what();
}
}
With VC++-2008 this gives:
exception: give me 5
But now I wonder why the message "give me 5" from the local object msg is still available in the catch-block? By the time the message is printed both the stream- and the temporary string-object should have been deleted? Btw: This way of generating a message for an exception seems also to work accross several functions and also if new memory is allocated in the catch-block before printing the exception.
Or is it necessary to define a custom exception class with a std::string member in order to safely keep the message until printing it.
It's perfectly safe. The constructor that takes a C string as a single parameter makes a copy of the string. The constructor that takes a C string and a length parameter allow you to specify no memory be allocated and stores a pointer to the string (the length parameter is ignored).
Note that these two constructors are extensions to the std::exception class and are not standard. Also be aware that the constructor that takes a C string as a single parameter is not marked as explicit.
It's OK.
Per §15.1/3:
Throwing an exception copy-initializes (8.5, 12.8) a temporary object,
called the exception object.
and §15.1/4:
The memory for the exception object is allocated in an unspecified
way, except as noted in 3.7.4.1. If a handler exits by rethrowing,
control is passed to another handler for the same exception. The
exception object is destroyed after either the last remaining active
handler for the exception exits by any means other than rethrowing...
so after throw expression:
the expression will be copied (new object will be created by copy constructor) and you shouldn't worry about the local object.
About the msg and const char* which you're worrying... here is Microsoft's implementation:
exception::exception(const char * const & _What)
: _Mywhat(NULL), _Mydofree(false)
{
_Copy_str(_What);
//^^^^^^^^^^^^^^^^^
}
void exception::_Copy_str(const char * _What)
{
if (_What != NULL)
{
const size_t _Buf_size = strlen(_What) + 1;
_Mywhat = static_cast<char *>(malloc(_Buf_size));
if (_Mywhat != NULL)
{
_CRT_SECURE_STRCPY(const_cast<char *>(_Mywhat), _Buf_size, _What);
//^^^^^^^^^^^^^^^^^^
_Mydofree = true;
}
}
}
It copies the _What not just storing the pointer.
No, it's not safe, because std::exception doesn't have a constructor taking a char* in the standard. You are using an MS extension. To make it portable and safe, use std::runtime_error instead, to which you can pass a std::string in the ctor.

exception handling a constructor

This was an interview question of me.
Surprisingly i never thought of this kinda question to myself.
can we have exception handling inside a constructor c++?
in tense and not thinking much i said "yes we could probably do it in a constructor.lets say we are allocating some memory using new operator to a pointer member and it throws a bad alloc exception,in this way there is a possibility of exceptions being raised"
Then later i thought that constructors can never return a value.So how can an exception inside a constructor caught.now i am asking this to myself!
can anybody pls help me to come out of this confusion?
See this GOTW Constructor Failures question which addresses your query somewhat and goes on to say it is a waste of time.
Constructors don't have a return type,
so it's not possible to use return
codes. The best way to signal
constructor failure is therefore to
throw an exception. If you don't have
the option of using exceptions, the
"least bad" work-around is to put the
object into a "zombie" state by
setting an internal status bit so the
object acts sort of like it's dead
even though it is technically still
alive.
You would catch the exception in the calling code, not within the constructor.
See How can I handle a constructor that fails? for further details (actually, I'd suggest reading the whole page about exception handling, truly enlightening).
Exception handling and return type are completely different. when the program find the exception in constructor, it throws the exception to nearly by catch block [if used] or thrown to caller (main()). in this case, we have catch block in constructor and exception handled by it. Once exception handled, the remaining statement in the constructor/function will be started executing. see the below example,
class A
{
public:
A(){
printf("Hi Constructor of A\n");
try
{
throw 10;
}
catch(...)
{
printf("the String is unexpected one in constructor\n");
}
printf("Hi Constructor of A\n");
}
~A(){
printf("Hi destructor of A\n");
}
};
int main()
{
try{
A obj ;
throw "Bad allocation";
}
catch(int i)
{
printf("the Exception if Integer is = %d\n", i);
}
catch(double i)
{
printf("the Exception if double is = %f\n", i);
}
catch(A *objE)
{
printf("the Exception if Object \n");
}
catch(...)
{
printf("the Exception if character/string \n");
}
printf("Code ends\n");
return 0;
}
This produce Output:
Start: Constructor of A
the String is unexpected one in constructor
End: Constructor of A
Hi destructor of A
the Exception if character/string
Code ends
C++ has try-catch clauses similar to those of other languages. A tutorial can be found online: http://www.cplusplus.com/doc/tutorial/exceptions/
EDIT: example turned into fully working code
#include <iostream>
using namespace std;
class A
{
public:
void f(){
throw 10;
}
A(){
try{
f();
}
catch(int e){
cout << "Exception caught\n";
}
}
};
int main (int argc, const char * argv[])
{
A a;
return 0;
}
This produces output:
Exception caught