Reputation: 21
I know in C that error code is the way to handle error. But why exception handling appear? What is the history there? What is the advantage of exception handling when compare to error code?
Thanks a lot for any information.
Upvotes: 1
Views: 1066
Reputation: 16449
Short answer - it lets you deal with error checking only when you really care.
Without exceptions, you find that a lot of your code is about error checking - whenever you call a function, you must check if it returned an error, and if it did - return an error to your caller.
With exceptions, Most of your code can simply call functions, and ignore failure. A top-level function would run everything in a try-catch block, and any exception somewhere will be caught and handled.
It assumes that you don't really care which specific error occurred. But you normally don't.
This way, exceptions allow you to write clearer code, that mostly deals with what you want to do, not with what could go wrong (without sacrificing correct behavior when things do go wrong).
Upvotes: 1
Reputation: 203
The link that sled provided can answer your question: http://docs.oracle.com/javase/tutorial/essential/exceptions/advantages.html
Upvotes: 0
Reputation: 11474
Exception handling works by transferring the execution of a program to an appropriate exception handler when an exception occurs.
For ex: Your website displays the users bank account details.
Suddenly if the bank database is down, imaging how the user would feel if an abrupt error page with numerous lines of java exception messages spewed all over the screen?
First of all, it would be embarrassing and second of all, the user will get annoyed.
Instead, if your code catches this database down scenario and displays a graceful message on screen saying "We are currently experiencing some difficulties in our system. Kindly try after some time. Thank you" it would be much better isn't it?
That is exactly why we have or rather why we need Exception Handling.
Upvotes: 1
Reputation: 10947
In the C language exceptions are not available. So, the typical way for error handling is to let functions return error values (which should be checked by the calling function).
In modern languages (e.g., C++, Java, etc.) exceptions are available. They allow to propagate the error until some component can handle it. For example, the calling function may not be capable of handling the error of the called function. Through excpetions, the error can be propagated at higher layers where it can be handled.
See here for more information.
Upvotes: 4