Click to See Complete Forum and Search --> : Try / Catch


kenrus
May 7th, 2008, 04:46 PM
Can someone point me to a web page or a book that contains a good explanation of using the try and catch statements in C++.

I think I basically understand their use, but I have never really used them before. I want to make sure I have a good understanding of them before I really begin to use them in production software.

Thanks for any help.

Kendall

anantwakode
May 7th, 2008, 11:28 PM
Hi,

this link may be useful to you...

http://msdn.microsoft.com/en-us/library/4t3saedz.aspx

-Anant

ajbharani
May 7th, 2008, 11:33 PM
MSDN! Its always nice :D

http://msdn.microsoft.com/hi-in/library/4t3saedz(en-us,VS.80).aspx

Happy learning! :)

Bharani.

Zaccheus
May 8th, 2008, 03:59 AM
One thing the MSDN intro seems to neglect is that ideally all exceptions should be derived from std::exception.

kenrus
May 8th, 2008, 10:07 AM
Those links have proven to be very helpful. I appreciate the information.

However, I am also looking for information on the hows and whys of using try catch as opposed to returning error codes.

exterminator
May 8th, 2008, 10:09 AM
1) Know what will throw exceptions and when.
2) Throw your own exceptions by value (a temporary), and catch as a reference /*to const if possible*/.
3) Do not fill your code with catch(...). Use them rarely.
4) Do not catch exceptions that you cannot handle.
5) Catch exceptions that you can partially handle and then re-throw them.
6) Exception specifications are good but I don't see them much in practice in C++ apart from empty throw() saying that a function doesn't throw.
7) DO not over-use exceptions. Be comfortable distinguishing an exception and a logical program error.
8) Derive your own exception classes from std::exception class. But don't make too many of them.
9) Do not throw any type of exception esp. those not derived from std::exception and the fundamental types, for example, int, const char* etc.
10) Make your code exception safe - this is not really related to exception handling but you should write code that doesn't fall apart in case an exception is throw. Search the web for David Abraham's writings on exception safety.