Take the 2-minute tour ×

Several resources are describing the topic "Exception Handling" like Wikipedia and vast more number of resources. But very few of them explained that what is the Exception itself. Maybe they assumed that its very obvious. I could find a good short explanation on Oracle documentation:


The rest of this paper is about exception on Java programming. But I do not understand Java well to read the entire of documentation. I need a clarify on exception.


  • I need an example of Exception. For example in C++.
  • And I need to know what is its difference by bug?
share|improve this question

closed as too broad by Balog Pal, SK9, rubenvb, towi, skuntsel Jun 30 '13 at 21:20


Just think of it as a very powerful GOTO. With the ability to jump from one method to another and the ability to find out why the jump was taken. –  Hans Passant Jun 30 '13 at 14:01
For example I can clarify object that it is like an object in real world and also an instruct that can be changed... But this definition is dim for me! –  Mohammad Etemaddar Jun 30 '13 at 14:03
@HansPassant : I think that exception is a bug "as described in the Defenition. and not a powerful thing like goto! –  Mohammad Etemaddar Jun 30 '13 at 14:06
@MohammadEtemaddar A bug is something that the programmer does not intend to happen, and does not anticipate. An exception indicates an unusual and often undesired event, but one that is fully expected to occur under certain circumstances. –  jogojapan Jun 30 '13 at 14:14
@jogojapan But it can also happen that a bug (from my own program or from another library) is the cause of an exception. –  leonbloy Jun 30 '13 at 14:29
add comment

3 Answers

Conceptually, an exception is a scenario that shouldn't happen in a normal run of your program. For example, a remote server being unavailable, an input being in an incorrect format, a file not being found, the system running out of memory... Depending on the kind and the circumstances, it may or may not be possible for the program to handle it.

Technically, an exception is represented as a simple object. Exception objects are kind of special in the sense that they can be "thrown" from an inner level of execution to an outer level that "catches" them, typically abandoning the code in all levels between the thrower and the catcher.

C++, Java and C# are a few examples of many languages that have a form of exception handling mechanism. Strictly speaking, C does not have the concept of exceptions (out-of-the-box, at least).

share|improve this answer
add comment

"Throwing an exception" (sometimes also called "raising an exception") is a way to end a function when, for some reason, the function cannot complete the task it is expected to complete.

Example: You have a function f that takes a float argument and is expected to compute and return its natural logarithm. Now at some point during the calculations it turns out that the argument that it was passed is 0. There is no way to compute the logarithm of 0, so what should the function do?

One way to handle this situation is to return a special value (such as NaN, the not-a-number value of float), but this can be misleading to the caller of the function: The function was called on some variable, and returned some value. All looks normal, while in reality nothing is normal – the function could not do its job.

Therefore, another way of handling this is to throw an exception. The effect is that the function ends, but does not return any value. Now, obviously, the calling function has a problem, because the normal flow of things has been disturbed: No value was returned from the function call. There are two possibilities for what can happen next: Either the calling function was prepared for this by having put the call of f in a try-catch clause:

try {
  log_of_val = f(val);
} catch (const exception &e) {
   /* Description of what to do when
      an exception is thrown by f. */

If the exception that is thrown by f matches the type of exception defined in one of the catch-clauses, then the first such catch-clause is executed.

If there is no such catch-clause, the exception is thrown again, i.e. the calling function also ends abruptly and the caller of the caller is stopped to check whether there is some catch-code for the exception. If not, it also ends and that functions calling function is stopped, and so on, until the top of the call stack is reached (i.e. the level of main) and if there is still no catch-clause there, the entire program is terminated and the operating system is informed of the abortion of the process.

So an exception has the power to bring down the entire process if there is no appropriate catch-clause. But an exception is far better than simply calling something like exit(1), because it does not immediately terminate the process. It first gives the caller a chance to react to the problem, and then the caller's caller, and so on.

The exception throwing mechanism also ensures that local variables are properly destructed and de-allocated before the current function ends. So, as far as automatic variables and dynamic memory that is managed by smart pointers and the like is concerned, you won't get memory leaks and similar problems.

To sum up, exceptions (and the whole throwing and catching mechanism) is a way to deal with unusual, but possible and to some extent expected events in the flow of a program. Typically, it's events that can occur in a function call that render the proper execution of the function impossible, but that cannot be prevented from within the function. These events are often the responsibility of the calling function if it passes unsuitable arguments, or of the user who gives unsuitable input to the program. Also problems related to the state of the system, such as insufficient memory, tend to be handled by throwing exceptions.

But unlike bugs, the programmer who wrote a function anticipated the possiblility of the problem and prepared the code with suitable throw and catch code to deal with it by having the program shut down in a controlled way, or otherwise react to the problem appropriately.

Regarding the core of your question: What is the exception itself? The exception is an object created at the time when the "exception is thrown". You could view it as some kind of replacement for the return value, because the exception object is in fact passed to the caller, in a similar way as the return value would. But unlike with an actual return value, the caller is informed that what has happened is an exception and that it must handle this in the way I've described above. Further more, the data type of the exception is not the data type declared as return type of the function. In fact, it can be (almost) any data type. In particular, it can be a complex object with member variables that are initialized with values that describe the circumstances of the exception. A typical exception object is C++ is of class type, often (but not necessarily) defined as something like this:

#include <exception>

class my_exception : public std::exception
  explicit my_exception(const char *description)
    : std::exception() , description_(description)
  { }

  virtual const char *what() const noexcept
  { return description_; }

  const char *description_;

So it's a user-defined object that is constructed on a string, stores a pointer to the string internally, and provides a member function what() that returns the string. The idea is that the string is defined when the exception is thrown, and that it contains some description of the problem.

The caller of f can then catch this type of exception by enclosing the call to f in a try-clause and adding a catch-clause for my_exception:

} catch (const my_exception &e) {
   std::cerr << "A problem has occurred when evaluating f(): "
             << e.what()
             << std::endl;

In this example, we use the exception object's what() function to print a description of the problem. After the catch-clause is completed, the caller will continue as normal. (If this is not desired, throw; can be used inside the catch-clause to re-throw the exception so it is passed to the caller's caller, and so on.)

Note, again, that exception can be user-defined objects, and they can be derived from std::exception, and they can override the what() function to return a problem description as a string, but none of this is necessary. You can also throw the string itself, or an int as exception.

share|improve this answer
add comment

Exception is an object which you throw during executing something IF anything goes wrongs.

Like that when you are "try"ing to execute the method, you can "catch" anything that ges wrong without crashing your program.

void doSmth()
    throw Exception("Not Good!")

Then whenever you want to call doSmth()

catch (Exception &e)
  cout << e.what() << endl;

this way, if somthing went wrong while executing doSmth you can figure it out without you application being crashed.

share|improve this answer
add comment
