Try/Catch NumberFormatException Tutorial

The NumberFormatException class is commonly thrown when an attempt is made to convert a string to a number. The NumberFormatException class is derived from RuntimeException. The RuntimeException class is an important class to mention because all subclasses that are derived from RuntimeException (and Error) are referred to as unchecked exceptions. I will be discussing the topic of unchecked versus checked exceptions in a future tutorial.

This tutorial builds on concepts from the following tutorials:



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 TryCatchNFE
C:\Java>cd TryCatchNFE
C:\Java\TryCatchNFE>Notepad TryCatchNFE.java

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


class TryCatchNFE {
    public static void main(String args[]) {
        Box box1 = new Box(5, 5, 8);
        Box box2 = new Box("10", "2", "4");

        System.out.println("The volume of box1 is: " + box1.getVolume());
        System.out.println("The volume of box2 is: " + box2.getVolume());
    
        Box box3 = new Box("Five", "Seven", "Three");
        //try {
        //    Box box3 = new Box("Five", "Seven", "Three");
        //} catch (NumberFormatException nfe) {
        //    System.out.println("String arguments must contain valid digits, unable to create box.");
        //}
    }
}

class Box {
    private int length = 0;
    private int height = 0;
    private int width = 0;

    Box (int length, int height, int width) {
        this.length = length;
        this.height = height;
        this.width = width;
    }

    Box (String length, String height, String width) {
        this.length = Integer.parseInt(length);
        this.height = Integer.parseInt(height);
        this.width = Integer.parseInt(width);
    }

    int getVolume() {
        return (length * height * width);
    }
}

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


C:\Java\TryCatchNFE>javac TryCatchNFE.java
C:\Java\TryCatchNFE>java TryCatchNFE



Final thoughts

It is worth mentioning again that NumberFormatException is derived from RuntimeException which makes it an unchecked exception.


Tutorials