Exception handling: dealing with errors
Ever since the beginning of programming languages, error handling has been one of the most difficult issues. Because its so hard to design a good error handling scheme, many languages simply ignore the issue, passing the problem on to library designers who come up with halfway measures that work in many situations but that can easily be circumvented, generally by just ignoring them. A major problem with most error handling schemes is that they rely on programmer vigilance in following an agreed-upon convention that is not enforced by the language. If the programmer is not vigilantoften the case if they are in a hurrythese schemes can easily be forgotten.
Exception handling wires error handling directly into the programming language and sometimes even the operating system. An exception is an object that is thrown from the site of the error and can be caught by an appropriate exception handler designed to handle that particular type of error. Its as if exception handling is a different, parallel path of execution that can be taken when things go wrong. And because it uses a separate execution path, it doesnt need to interfere with your normally executing code. This makes that code simpler to write because you arent constantly forced to check for errors. In addition, a thrown exception is unlike an error value thats returned from a method or a flag thats set by a method in order to indicate an error conditionthese can be ignored. An exception cannot be ignored, so its guaranteed to be dealt with at some point. Finally, exceptions provide a way to reliably recover from a bad situation. Instead of just exiting the program, you are often able to set things right and restore execution, which produces much more robust programs.
Javas exception handling stands out among programming languages, because in Java, exception handling was wired in from the beginning and youre forced to use it. If you dont write your code to properly handle exceptions, youll get a compile-time error message. This guaranteed consistency can sometimes make error handling much easier.
Its worth noting that exception handling isnt an object-oriented feature, although in object-oriented languages the exception is normally represented by an object. Exception handling existed before object-oriented languages.