Handling unusual and error conditions - exceptions
Archive - Originally posted on "The Horse's Mouth" - 2010-02-03 22:47:41 - Graham Ellis
"I can't answer that question in the way you expect" ... that's something that may be said to you occasionally - you ask someone what suit a playing card is that they're holding and they cannot tell you because it is a joker, or you ask what number is written on a piece of paper when the paper is blank.
The way we handle situations like this in many modern programming languages is through excpetions - where a keyword such as try is used to indicate a block of code that may potentially have a problem, and then we use catch or rescue to tell it what to do if something goes wrong.
Exceptions are blocks, and although you may not think so at first the scope (size) of block is every bit as important as the scope of an if or while block.
Sometimes, exceptions will be processed in there entirety by the function / method in which the problem occurs, but at other times you'll want to throw the excpetion back up to the calling level; in that case, you'll need to put a try block in the calling code too. There's a new example of this (in Ruby) on our web site from today's Ruby Programming Course ... and the example is [here]. We have an example showing how it's coded in Python [here], and one from C++ [here}. We've got examples of the format of exceptions in Java on our site too - see [here].