Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When and how should I use exception handling?

I am reading about exception handling. I got some information about what exception handling is, but I have a few questions:

  1. When to throw an exception?
  2. Instead of throwing an exception, can we use a return value to indicate the error?
  3. If I protect all my functions by try-catch blocks, won't it reduce the performance?
  4. When to use exception handling?
  5. I saw a project where each and every function in that project contained a try-catch block (i.e. code inside the entire function is surrounded by try-catch block). Is this a good practice?
  6. What is the difference between try-catch and __try __except?
like image 566
Umesha MS Avatar asked Dec 22 '10 05:12

Umesha MS


People also ask

When should exception handling be used Java?

As you've seen, Java offers you two general types of exceptions: The checked and the unchecked exception. You should use a checked exception for all exceptional events that can be expected and handled by the application. You need to decide if you want to handle it within a method or if you specify it.

Why should we use exceptions?

Exceptions provide the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. In traditional programming, error detection, reporting, and handling often lead to confusing spaghetti code.

What is an exception and why do we need to handle it?

Why do we need to handle exceptions? Explanation: The exceptions should be handled to prevent any abnormal termination of a program. The program should keep running even if it gets interrupted in between.

Why should we use exception handling C++?

Exceptions are preferred in modern C++ for the following reasons: An exception forces calling code to recognize an error condition and handle it. Unhandled exceptions stop program execution. An exception jumps to the point in the call stack that can handle the error.


2 Answers

Here's quite comprehensive guide on exceptions that I think is a Must Read:

Exceptions and error handling - C++ FAQ or C++ FAQ lite

As a general rule of thumb, throw an exception when your program can identify an external problem that prevents execution. If you receive data from the server and that data is invalid, throw an exception. Out of disk space? Throw an exception. Cosmic rays prevent you from querying the database? Throw an exception. But if you get some invalid data from inside your very own program - don't throw an exception. If your problem comes from your own bad code, it's better to use ASSERTs to guard against it. Exception handling is needed to identify problems that program cannot handle and tell them about the user, because user can handle them. But bugs in your program are not something the user can handle, so program crashing will tell not much less than "Value of answer_to_life_and_universe_and_everything is not 42! This should never happen!!!!11" exception.

Catch an exception where you can do something useful with it, like, display a message box. I prefer to catch an exception once inside a function that somehow handles user input. For example, user presses button "Annihilate all hunams", and inside annihilateAllHunamsClicked() function there's a try...catch block to say "I can't". Even though annihilation of hunamkind is a complex operation that requires calling dozens and dozens of functions, there is only one try...catch, because for a user it's an atomic operation - one button click. Exception checks in every function are redundant and ugly.

Also, I can't recommend enough getting familiar with RAII - that is, to make sure that all data that is initialized is destroyed automatically. And that can be achieved by initializing as much as possible on stack, and when you need to initialize something on heap, use some kind of smart pointer. Everything initialized on the stack will be destroyed automatically when an exception is thrown. If you use C-style dumb pointers, you risk memory leak when an exception is thrown, because there is noone to clean them up upon exception (sure, you can use C-style pointers as members of your class, but make sure they are taken care of in destructor).

like image 157
Septagram Avatar answered Oct 09 '22 04:10

Septagram


Exceptions are useful in a variety of circumstances.

First, there are some functions where the cost of calculating the pre-condition is so high it is better to just do the calculation and abort with an exception if it is found the pre-condition is not met. For example, you cannot invert a singular matrix, however to calculate if it is singular you calculate the determinant which is very expensive: it may have to be done inside the function anyhow, so just "have a try" at inverting the matrix and report an error if you can't by throwing an exception. This is basically an exception as negative pre-condition usage.

Then there are other cases where your code is already complex and passing error information up the call chain is difficult. This is partly because C and C++ have broken data structure models: there are other, better ways, but C++ doesn't support them (such as using monads in Haskell). This use is basically I couldn't be bothered to do it right so I'll throw an exception: its not the right way but it's practical.

Then there is the main use of exceptions: to report when external pre-conditions or invariants, such as sufficient resources like memory or disk space, are not available. In this case you will usually terminate the program, or a major subsection of it, and the exception is a good way of transmitting information about the problem. C++ Exceptions were designed for reporting errors which prevent the program continuing.

The exception handling model used in most modern languages including C++ is known to be broken. It is vastly too powerful. Theoreticians have now developed better models than the completely open "throw anything" and "maybe and maybe not catch it" model. In addition using type information to classify exceptions wasn't a very good idea.

So the best thing you can do is throw exceptions sparingly, when there's an actual error, and when there's no other way to deal with it and catch exceptions as close to the throw point as possible.

like image 29
Yttrill Avatar answered Oct 09 '22 06:10

Yttrill