CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ

Validate

Validate input data
Handle exceptions
How exceptions work

What happens when a method you want to call is risky?

  • Let's say you want to call a method in a class that you didn't write.
  • That method does something risky, something that might not work at runtime.
  • You need to know that the method you're calling is risky.
  • You then write code that can handle the failure if it does happen. You need to be prepared, just in case.

Methods in Java use exceptions to tell the calling code.

java's exception-handling mechanism is a clean, well-lighted way to handle "exceptional situations" that pop up at runtime; it lets you put all your error-handling code in one easy-to-read place. It's based on you knowing that the method you're calling is risky, so that you can write code to deal with that possibility. If you know you might get an exception when you call a particular method, you can be prepared for - possibly even recover from - the problem that caused the exception.

So how do you know if a method throws an exception?

How exceptions work

  • An exception is an object that contains information about an error that has occurred.
  • When an error occurs in a method, the method throws an exception.
  • If an exception is thrown when you're testing a console application, some information about the exception, including its name and stack trace, is displayed at the console.
  • A stack trace is a list of the methods that were called before the exception occurred. The list appears in reverse order, from the last method called to the first method called.
  • All exceptions are subclasses of the Exception class. The Exception class represents the most general type of exception, while the subclasses represent increasingly specific exceptions.
  • The class for an exception is usually stored in the same package as the class whose methods throw that type of exception.

Some of the classes in the Exception hierarchy

Exception
    RuntimeException
        NoSuchElementException
            InputMismatchException
        IllegalArgumentException
            NumberFormatException
        ArithmeticException
        NullPointerException

Three methods that might throw an exception

When your code calls a risky method - a method that declares an exception - it's the risky method that throws the exception back to you, the caller.

Class Method Throws
Scanner nextDouble() InputMismatchException
Integer parseInt(String) NumberFormatException
Double parseDouble(String) NumberFormatException

The console after an InputMismatchException has been thrown

import java.util.Scanner;

public class InvoiceApp
{
    public static void main(String[] args)
    {
        // welcome the user to the program
        System.out.println("Welcome to the Invoice Total Calculator");
        System.out.println();  // print a blank line

		// create a Scanner object named sc
		Scanner sc = new Scanner(System.in);

        // perform invoice calculations until choice isn't equal to "y" or "Y"
        String choice = "y";
        while (choice.equalsIgnoreCase("y"))
        {
		    // get the invoice subtotal from the user
            System.out.print("Enter subtotal:   ");
        	double subtotal = sc.nextDouble();

        	// calculate the discount amount and total
        	double discountPercent= 0.0;
        	if (subtotal >= 200)
        		discountPercent = .2;
        	else if (subtotal >= 100)
        		discountPercent = .1;
        	else
        		discountPercent = 0.0;
        	double discountAmount = subtotal * discountPercent;
        	double total = subtotal - discountAmount;

            // display the discount amount and total
        	String message = "Discount percent: " + discountPercent + "\n"
        	               + "Discount amount:  " + discountAmount + "\n"
                           + "Invoice total:    " + total + "\n";
        	System.out.println(message);

        	// see if the user wants to continue
        	System.out.print("Continue? (y/n): ");
        	choice = sc.next();
        	System.out.println();
		}
    }
}

Previous | How exceptions work | How to catch exceptions | Application | Exception-throwing code | Next