Home

Introduction to Exception Handling

 
 
 

Introduction

During the execution of a program, the computer will face two types of situations: those it is prepared to deal with and those it is not. Imagine you write a program that requests a number from the user:

import java.util.Scanner;

public class Exercise {
    public static void main(String[] args) {
	double side;
	Scanner scnr = new Scanner(System.in);

        System.out.println("Square Processing");
        System.out.print("Enter Side: ");
        side = scnr.nextDouble();

        System.out.println("\nSquare Characteristics");
        System.out.printf("Side:      %.2f\n", side);
        System.out.printf("Perimeter: %.2f\n", side * 4);
    }
}

This is a classic easy program. When it comes up, the user is asked to simply type a number. The number would then be multiplied by 4 and display the result. Here is an example of compiling and running the program:

Square Processing
Enter Side: 24.95

Square Characteristics
Side:      24.95
Perimeter: 99.80

Imagine that a user types something that is not a valid number, such as the name of a country or somebodyís telephone number. Since this program was expecting a number and it is not prepared to multiply a string to a number, it would not know what to do. The only alternative the compiler would have is to send the problem to the operating system, hoping that the OS would know what to do. What actually happens is that, whenever the compiler is handed a task, it would try to perform the assignment. If it cannot perform the assignment, for any reason it is not prepared for, it would produce an error. As a programmer, if you can anticipate the type of error that could occur in your program, you can identify the error yourself and deal with it by telling the compiler what to do when this type of error occurs.

Practical LearningPractical Learning: Introducing Exception Handling

  1. Start NetBeans if necessary.
    To start a new application, on the main menu, click File -> New Project...
  2. In the Categories section, make sure Java is selected.
    In the Projects section, make sure Java Application is selected.
    Click Next
     
    New Project
  3. Set the Project Name to Geometry8
  4. In the Create Main Class text box, replace Main with Central and click Finish
  5. To create a package, in the Projects window, under Geometry8, right-click Source Packages -> New -> Java Package...
  6. Set the Name to Geometry and click Finish
  7. To create a class, in the Projects window, under Geometry8, right-click Geometry -> New -> Java Class...
  8. In the Class Name text box, set the Name to Point and click Finish
  9. Complete the document with the following code:
     
    package Foundation;
    
    public class Point extends Object {
        protected int x;
    
        public Point() {
            this.x = 0;
        }
    
        public Point(int x) {
            this.x = x;
        }
    
        public int getX() {
            return x;
        }
    
        public void setX(int x) {
            this.x = x;
        }
    
        @Override
        public boolean equals(Object obj) {
            return super.equals(obj);
        }
    
        @Override
        public String toString() {
            return super.toString();
        }
    }
  10. To create a package, in the Projects window, right-click Geometry -> New -> Java Package...
  11. Set the Name to Quadrilaterals and click Finish
  12. To create a sub-package, in the Projects window, right-click Geometry.Quadrilaterals -> New -> Java Package...
  13. Type Parallelograms (as the name on the right side of the period) and click Finish
  14. To create a new class, in the Projects window, right-click Geometry.Quadrilaterals.Parallelograms -> New -> Java Class...
  15. In the Class Name text box, set the Name to Rectangle
  16. Complete the document with the following code:
     
    package Geometry.Quadrilaterals.Parallelograms;
    
    public class Rectangle {
        protected double length;
        protected double height;
    
        public Rectangle() {
            this.length = 0.00;
            this.height = 0.00;
        }
    
        public Rectangle(double length, double height) {
            this.length = length;
            this.height = height;
        }
    
        public double getLength() {
            return length;
        }
    
        public void setLength(double length) {
            if( this.length <= 0.00 )
                this.length = 0.00;
            else
                this.length = length;
        }
    
        public double getHeight() {
            return height;
        }
    
        public void setHeight(double height) {
            if( this.height <= 0.00 )
                this.height = 0.00;
            else
                this.height = height;
        }
    
        public double calculatePerimeter() {
            return (this.length + this.height) * 2; 
        }
    
        public double calculateArea() {
            return this.length * this.height; 
        }
    }
  17. Access the Central.java file and change its document as follows:
     
    package geometry8b;
    import java.util.Scanner;
    import Geometry.Quadrilaterals.Parallelograms.Rectangle;
    
    public class Central {
        private static double specifyMeasure(String name) {
            double value = 0.00;
            Scanner scnr = new Scanner(System.in);
            
            System.out.print("Enter the " + name + ": ");
            value = scnr.nextDouble();
            
            return value;
            
        }
        
        private static void show(Rectangle figure) {
            System.out.println("Rectangle Characteristics");
            System.out.printf("Length:    %.2f\n", figure.getLength());
            System.out.printf("Height:    %.2f\n", figure.getHeight());
            System.out.printf("Perimeter: %.2f\n", figure.calculatePerimeter());
            System.out.printf("Area:      %.2f\n", figure.calculateArea());
        }
        
        public static void main(String[] args) {
            double dLength = specifyMeasure("length");
            double dHeight = specifyMeasure("height");
            
            Rectangle recto = new Rectangle(dLength, dHeight);
            show(recto);
        }
    
    }
  18. Press F6 to execute the application
  19. When asked to enter the length, type What and press Enter
     
    Enter the length: 
    What
    Exception in thread "main" java.util.InputMismatchException
            at java.util.Scanner.throwFor(Scanner.java:840)
            at java.util.Scanner.next(Scanner.java:1461)
            at java.util.Scanner.nextDouble(Scanner.java:2387)
            at geometry8.Central.specifyMeasure(Central.java:11)
            at geometry8.Central.main(Central.java:26)
    Java Result: 1
 
 

 

 

Trying an Exception

An exception is an unusual situation that could occur in your program. As a programmer, you should anticipate any abnormal behavior that could be caused by the user entering wrong information that could otherwise lead to unpredictable results. The ability to deal with a programís abnormal behavior is called exception handling. Java provides many keywords and built-in classes to handle an exception. You proceed with a top-down approach.

To start handling an exception, create a section of code that includes the normal flow of the program. This section starts with the try keyword followed by an opening curly bracket and a closing curly bracket. The section in the curly brackets is the body. In it, you write the normal code. Here is an example:

import java.util.Scanner;

public class Exercise {
    public static void main(String[] args) {
	double side;
	Scanner scnr = new Scanner(System.in);

        try {
            System.out.println("Square Processing");
            System.out.print("Enter Side: ");
            side = scnr.nextDouble();

            System.out.println("\nSquare Characteristics");
            System.out.printf("Side:      %.2f\n", side);
            System.out.printf("Perimeter: %.2f\n", side * 4);
	}
    }
}

Catching an Exception

Just after the try section, that is, after the closing curly bracket of try, you create a new section that uses the catch keyword. This new section uses the following formula:

catch(ExceptionClass) { WhatToDo }

As you can see, this section starts with the catch keyword with parentheses. The parentheses behave like those of a method. You must pass an argument. At a minimum, you can pass a class named Exception and a name for the argument. After the closing the parenthesis, create a body for the section. Like a normal body, this starts with an opening curly bracket and ends with a closing curly bracket.

Based on this, the basic formula of exception handling is:
 

try {
    // Try the program flow
}
catch(Exception arg) {
    // Catch the exception
}

Here is an example of a program that handles an exception:

import java.util.Scanner;

public class Exercise {
    public static void main(String[] args) {
	double side = 0;
	Scanner scnr = new Scanner(System.in);

	try {
            System.out.println("Square Processing");
            System.out.print("Enter Side: ");
            side = scnr.nextDouble();

            System.out.println("\nSquare Characteristics");
            System.out.printf("Side:      %.2f\n", side);
            System.out.printf("Perimeter: %.2f\n", side * 4);
	}
	catch(Exception e) {
	}
    }
}

Here is an example of running the program:

Square Processing
Enter Side: 22.98

Square Characteristics
Side:      22.98
Perimeter: 91.92

This is another example of running the same program:

Square Processing
Enter Side: Yes

Practical LearningPractical Learning: Introducing Vague Exceptions

  1. Change the Central.java file as follows:
     
    package geometry8b;
    import java.util.Scanner;
    import Quadrilaterals.Parallelograms.Rectangle;
    
    public class Central {
        private static double specifyMeasure(String name) {
            double value = 0.00;
            Scanner scnr = new Scanner(System.in);
            
            try {
                System.out.print("Enter the " + name + ": ");
                value = scnr.nextDouble();    
            }
            catch(Exception exc) {
    
            }
            
            return value;
        }
        
        private static void show(Rectangle figure) {
            System.out.println("Rectangle Characteristics");
            System.out.printf("Length:    %.2f\n", figure.getLength());
            System.out.printf("Height:    %.2f\n", figure.getHeight());
            System.out.printf("Perimeter: %.2f\n", figure.calculatePerimeter());
            System.out.printf("Area:      %.2f\n", figure.calculateArea());
        }
        
        public static void main(String[] args) {
            double dLength = specifyMeasure("length");
            double dHeight = specifyMeasure("height");
            
            Rectangle recto = new Rectangle(dLength, dHeight);
            show(recto);
        }
    
    }
  2. Press F6 to execute the application
  3. When asked to enter the length, type What and press Enter
  4. When asked to enter the height, type 24.55 and press Enter
     
    Enter the length: What
    Enter the height: 24.55
    Rectangle Characteristics
    Length:    0.00
    Height:    24.55
    Perimeter: 49.10
    Area:      0.00

Exceptions and Custom Messages

As mentioned already, if an error occurs when processing the program in the try section, the compiler transfers the processing to the next catch section. You can then use the catch section to deal with the error. At a minimum, you can display a message to inform the user.

To display a message resulting from an exception, create it in the catch block. Here is an example:

import java.util.Scanner;

public class Exercise {
    public static void main(String[] args) {
	double side = 0;
	Scanner scnr = new Scanner(System.in);

	try {
            System.out.println("Square Processing");
            System.out.print("Enter Side: ");
            side = scnr.nextDouble();

            System.out.println("\nSquare Characteristics");
            System.out.printf("Side:      %.2f\n", side);
            System.out.printf("Perimeter: %.2f\n", side * 4);
	}
	catch(Exception exc) {
	    System.out.println("The value you provided for the side is invalid");
	}
    }
}

Here is an example of running the program:

Square Processing
Enter Side: 24

Square Characteristics
Side:      24.00
Perimeter: 96.00

Here is another example of running the program:

Square Processing
Enter Side: 26GW
The value you provided for the side is invalid

You can provide any message you want. The idea is to be as help and explicit as possible so the user may know what the problem was.

Practical LearningPractical Learning: Displaying Custom Messages

  1. To display custom messages to the user, change the OrderProcessing.cs file as follows:
     
    package geometry8b;
    import java.util.Scanner;
    import Quadrilaterals.Parallelograms.Rectangle;
    
    public class Central {
        private static double specifyMeasure(String name) {
            double value = 0.00;
            Scanner scnr = new Scanner(System.in);
            
            try {
                System.out.print("Enter the " + name + ": ");
                value = scnr.nextDouble();    
            }
            catch(Exception exc) {
                System.out.println("Something went wrong!!!");
            }
            
            return value;
        }
        
        private static void show(Rectangle figure) {
            System.out.println("Rectangle Characteristics");
            System.out.printf("Length:    %.2f\n", figure.getLength());
            System.out.printf("Height:    %.2f\n", figure.getHeight());
            System.out.printf("Perimeter: %.2f\n", figure.calculatePerimeter());
            System.out.printf("Area:      %.2f\n", figure.calculateArea());
        }
        
        public static void main(String[] args) {
            double dLength = specifyMeasure("length");
            double dHeight = specifyMeasure("height");
            
            Rectangle recto = new Rectangle(dLength, dHeight);
            show(recto);
        }
    
    }
  2. Execute the application to test it
  3. When asked to enter the values, type anything you want and press Enter each time
     
    Enter the length: What
    Something went wrong!!!
    Enter the height: 44.68
    Rectangle Characteristics
    Length:    0.00
    Height:    44.68
    Perimeter: 89.36
    Area:      0.00
  4. Execute the application again and test it with other values
 
 
 

Previous Copyright © 2009-2012, FunctionX, Inc. Next