Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between using try-Catch exception handler and if else condition check? [duplicate]

I have used in many places if...else statements, however I'm new to exception handling. What is the main difference among these two?

for eg:

 int *ptr = new (nothrow) int[1000];
 
 if (ptr == NULL) {
     // Handle error cases here...
 }

OR

  try
  {
    int* myarray= new int[1000];
  }
  catch (exception& e)
  {
    cout << "Standard exception: " << e.what() << endl; 
  }

So we are using here standard class for exception which has some in build function like e.what(). So it may be advantage. Other than that all other functionality handling we can do using if...else also. Is there any other merits in using exception handling?

like image 221
Newbee Avatar asked Aug 19 '13 06:08

Newbee


1 Answers

To collect what the comments say in an answer:

since the standardization in 1998, new does not return a null pointer at failure but throws an exception, namely std::bad_alloc. This is different to C's malloc and maybe to some early pre-standard implementations of C++, where new might have returned NULL as well (I don't know, tbh).

There is a possibility in C++, to get a nullpointer on allocation failure instead of an exception as well:

int *ptr = new(std::nothrow) int[1000];

So in short, the first code you have will not work as intended, as it is an attempt of C-style error handling in the presence of C++ exceptions. If allocation fails, the exception will be thrown, the if block will never be entered and the program probably will be terminated since you don't catch the bad_alloc.

There are lots of articles comparing general error handling with exceptions vs return codes, and it would go way to far trying to cover the topic here. Amongst the reasons for exceptions are

  • Function return types are not occupied by the error handling but can return real values - no "output" function parameters needed.
  • You do not need to handle the return of every single function call in every single function but can just catch the exception some levels up the call stack where you actually can handle the error
  • Exceptions can pass arbitraty information to the error handling site, as compared to one global errno variable and a single returned error code.
like image 56
Arne Mertz Avatar answered Sep 23 '22 17:09

Arne Mertz