Exception Handling: Try and Catch Tutorial

There are tons and tons of methods in Java that are predisposed to causing exceptions and believe it or not, that is a good thing. It is too early in the topic of exception handling to explain at this point, but once you understand all of the concepts, you will see why. The very heart and soul of exception handling relies on two Java keywords: try and catch. If you've ever watched that show Mythbusters, then you know that Adam and Jamie just love to blow stuff up. They poke and prod and try everything under the sun to break stuff and sometimes they just blow it up in the end. If they were programmers I imagine it would go something like this ... "Hey Adam, let's try this line of code and if it goes kaboom, then we'll catch the pieces and see if we can salvage anything". Programming is just like real life; think of a method as something of a chainsaw ... a chainsaw is designed to cut down trees, but there is nothing stopping you from trying to cut the door off of your car and if you try that there will be exceptions like a trip to the ER, a broken chain, etc. Methods are designed to perform a specific task and depending on their level of complexity it is impossible to anticipate how someone may choose to utilize the method, so if you are the one writing the method you will try to anticipate specific abuses and throw exceptions for those situations.
When I invoke a method that could have questionable results, I enclose that method in a try block. A try block looks like this:
try {
        questionableMethod();
}
The above code is incomplete, we are trying something, but what happens if that statement goes kaboom? That is the purpose of a catch block. At a minimum a complete try and catch statement looks like this:
try {
        questionableMethod();
} catch (ExceptionType varName) {
        doSomethingElse();
}
In the example above, the most important and frustrating thing to understand is the ExceptionType. The ExceptionType will appear cryptic and intimidating and the only way to understand ExceptionTypes is through trial and error. You will need to thoroughly understand how to use the online Java API if you really want to understand exception handling.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md ExceptionTryCatch
C:\Java>cd ExceptionTryCatch
C:\Java\ExceptionTryCatch>Notepad ExceptionTryCatch.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class ExceptionTryCatch {
    public static void main(String args[]) {
        for(String temp : args) {
            tripleIt(temp);
        }        
    }

    static void tripleIt(String s) {
        Integer i = Integer.valueOf(s);
        System.out.println("Triple the value of " + i + " is: " + (i*3));
    }
}
        /*try {
            Integer i = Integer.valueOf(s);
            System.out.println("Triple the value of " + i + " is: " + (i*3));
        } catch (NumberFormatException nfe) {
            System.out.println("Cannot triple " + s + ", try again with a valid number.");
        }*/



Now switch back to the command prompt (CMD) and type in javac ExceptionTryCatch.java and press Enter.
Now type in java ExceptionTryCatch and press Enter.


C:\Java\ExceptionTryCatch>javac ExceptionTryCatch.java
C:\Java\ExceptionTryCatch>java ExceptionTryCatch 12 30 DAN 80
Triple the value of 12 is: 36
Triple the value of 30 is: 90
Cannot triple DAN, try again with a valid number.
Triple the value of 80 is: 240


Final thoughts

The only way to truly gain experience with understanding exception handling is with a lot of trial and error. It is not easy, but you will need to learn quite a few exception types before many of the concepts sink in. Referencing the Java API every time you use a method may seem tedious, but it is necessary. Looking at the java.lang package raw source code from the src.zip is also a great way to solidify your understanding.


Tutorials