Tuesday 11 October 2011

Java: Catching Exceptions and the Finally Block

Last post before we move on to the chapter about either more intricate processes (multiple things happening at once, basically) OR we can go right into the GUI material (Graphic User Interfaces, click on buttons to do things etc.). Either way doesn't matter to me, they're both going to get done, but which would you guys like to see first? I'll put up a poll later if I work out how, and I'll spend all of tomorrow either answering questions or bullshitting so you have time to vote on it!

For now, let's get into the material. Catching exceptions, first. Well, we've already done throwing, right, so naturally something needs to catch it. I think we've seen this in the Stack program way earlier, the try-catch block. How this works is, you have a series of statements (the body) that has some chance of triggering an exception throwing, and you stuff that inside a try block, which is just a compound statement preceded by
the try keyword instead of say, an if keyword. Associated with this try block is 1 or more catch blocks. Each catch block corresponds to 1 exception being thrown. The reason for these exceptions being separated is so they're easier to deal with when you do run into them, because the catching block of code will tell you exactly what went wrong. Here's an example:


Here we have (in the executing code, not the pop method), an attempt to pop off some Stack<Car>, i. Trying to pop MAY result in an exception being thrown, so it's placed in a try block. Next we have the catch blocks. The first is to catch the exception we expect. Since exceptions are represented as objects, we'll pass it as a standard parameter, with a variable name to hold it. It's in this block now we have the recovering action(s). Save current data, or just ignore the command, whatever.
The last catch block is just to illustrate that you can have more than 1. This will catch all exceptions, unless it's already been caught by a previous catch block.

Remember, a lot of times, while far, far bulkier, testing all your code for exceptions tends to be better in the long term, even if it looks a-okay. I still won't do it, but I don't know what's best for me.


The finally block! Okay, so, in a try block, stuff is gone over to see if an exception will be thrown. If it isn't, the try block is executed. If it is, then you'll have whichever catch block be executed instead. At the end of this, you can have a finally block. This code will execute regardless of whether or not an exception has been found. You won't find this useful very often, but it's great when you do want it!


 That's it for now..Questions welcome! Comment, follow, subscribe, share etc, and see you tomorrow!


And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here (fixed), and feel free to throw loads of criticism at us. 

3 comments: