View Full Version : Java question for all you techies

03-11-2013, 07:24 AM
Hey, I'm trying to get my head around Java here and I'm just wondering how you're meant to be able to tell the difference between an "unchecked" and a "checked" exception.

I've decided to give try/catch statements a but I'm not sure what the difference is.

Any help will be rewarded with free internet cookies :)

03-12-2013, 12:45 PM
Basically, if your code throws a checked exception (or calls anything that throws a checked exception), the compiler requires that you declare that fact with "throws Whatever" at the class/function definition, or that you catch it. Unchecked exceptions have no such checking and will just propagate up the callstack. If you want, I can come up with some pseudocode to demonstrate the basic idea.

03-12-2013, 02:37 PM
I think I get the gist but a demo would be appreciated

12-15-2013, 12:19 PM
try {

// Open a file in here
// eat the contents of the file, or store it for winter (aka in a string)

} catch (FileNotFoundException e) {

// Code to handle the file not found
// Basically in here you soft handle the error, that is: make note of it for your program for the user "Ack, you gave me a bad file dummy"
// or if you can't do that, do something in here to correct the problem, or try something different like using different extensions

} catch (IOException e) {

// Code to handle the exception
// This is the 'General' catch if the first catch didn't catch that means there was another problem with the code.
// This is the 'fail safe' of using volatile code like file openers. With this catch block the code will never 'break'

} finally {

// Close your file <- really important
// Its common practice to put all resource clean up code in the finally block.
// This way it will always be called whether your try worked or not.


While in the catch block, you are returned the matching exception. Exceptions have a hierarchy of specific to less specific, with the least specific as 'Exception'. You could do just a catch(Exception e) as your last catch statement, but the code to handle it will have to be more general, like 'Oh it failed, email the admin, tell the user, and move on'. Instead of a more specific exception handling code, that says: "Oh if this didn't work lets try this!"

Also the variable e, which I'm using everywhere has lots of useful information in it. It will have the error message, the cause, the error code, where the code was called and more.