aanrv
aanrv

Reputation: 2241

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?

Upvotes: 10

Views: 4975

Answers (5)

Tony Delroy
Tony Delroy

Reputation: 106244

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

Upvotes: 13

user1733471
user1733471

Reputation:

The other reason is: code you write might as well be used as a part of larger project by somebody else. And since using built-in exception-handling routines is a standard, maintainers of the larger project are expecting that you handle your exceptions likewise, so that exception handling can be properly fulfilled at upper levels - not to speak of the fact, that using standard output as an error output is a dubious practice (it may be suppressed, for example; or not be used at all).

UPD: I misunderstood your question a little bit. The reason I described actually justifies manual exception throwing, but not using try...catch blocks.

Upvotes: 1

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145457

The question poses a false dichotomy. In Java and C# try-catch competes with if for cleanup on failure. In C++ it's mainly RAII technique (using destructors and single phase construction) that competes with if for cleanup on failure.

If the question had been about using exceptions versus using if, then it would have been more sensible and relevant to ordinary C++ programming.

Upvotes: -2

Brian Tiffin
Brian Tiffin

Reputation: 4126

I'm going to answer with a quote from one of my heroes, Martin Sústrik of ZeroMQ fame, taken from a blog entry at http://www.250bpm.com/blog:4

However, what's great for avoiding straightforward failures becomes a nightmare when your goal is to guarantee that no undefined behaviour happens. The decoupling between raising of the exception and handling it, that makes avoiding failures so easy in C++, makes it virtually impossible to guarantee that the program never runs info undefined behaviour.

And then add, I find I use try/catch for very high lever restart layers, more than anything else. Adding, that my opinion really doesn't matter. I'm of the belief that the choice behind how and why to use exception handling is very similar to the choice of liking green more than blue. Personal, and no input from others is ever likely to change it.

Upvotes: -2

James
James

Reputation: 9288

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)

Upvotes: 5

Related Questions