Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use try and catch() in C++?

I understand that try and catch() are used for exception handling, just in case an error or crash would occur in the program under certain cases. I also understand how they work. But why use try and catch()? Why not just use an if() statement that looks for a certain case and if that case is true, it does cout << //error code?

like image 210
aanrv Avatar asked Feb 14 '13 02:02

aanrv


2 Answers

Exception handling:

  • can be used with constructors and operators that have no opportunity to return a separate error code (they could set the object into some error state - which implies further memory usage - but the client code also has to remember to check for that error state later)
    • for example: user defined type - class X - supports notation x1 = x2 + x3 - where could an error code be returned?
  • can kick in as a specific class/struct data member is constructed in an initialiser list - avoiding further data member construction that may then be doomed or wasteful; by way of contrast, explicit error handling is only possible later in the constructor body
  • is more implicit - emphasising the normal successful flow of code, which can make it more concise, readable, maintainable
  • is factored differently - exceptions from many places can be caught in one place, which sometimes makes the error handling code itself more concise, readable, maintainable
  • concision benefits can actually lead to more reliable error handling in cases where the error handling would otherwise be repetitious
  • typically use their own memory area, independent of the stack used for local variables, function parameters, saving CPU registers and return addresses etc.; this means a throw statement may be able to reliably construct the exception object directly in that memory area even when remaining stack memory is smaller than the exception object (though that an implementation detail and not guaranteed by the Standard)
  • has a different performance profile, such that either can be faster in certain circumstances
  • facilitates propagation of richer error information from low level code up through intermediate code, which you may not "own" or want/be-able to change to propagate error codes C-style, to the point of handling
like image 104
Tony Delroy Avatar answered Sep 19 '22 12:09

Tony Delroy


try...catch does more. It unwinds the stack which calls the destructors for all automatically allocated objects since the try was entered. If you do it your suggested way you'll have to keep track of these object manually or you'll get memory issues (leaks, overwriting, stale pointers, double deletes)

like image 42
James Avatar answered Sep 19 '22 12:09

James