Reputation: 2241
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
Reputation: 106244
Exception handling:
X
- supports notation x1 = x2 + x3
- where could an error code be returned?Upvotes: 13
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
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
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
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