CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Exceptions

Exceptions handling
Exceptions
Throw statement

When to throw an exception

  • When a method encounters a problem that prevents it from completing its task, such as when the method is passed unacceptable argument values.
  • When you want to generate an exception to test an exception handler.
  • When you want to catch an exception, perform some processing, then throw the exception again so it can be handled by the calling method.

The syntax of the throw statement

throw Throwable;

How to use the throw statement

  • You use the throw statement to throw an exception.
  • You can name any object of type Throwable in a throw statement.
  • To throw a new exception, use the new keyword to call the constructor of the exception class you want to throw.
  • To throw an existing exception, you must first catch the exception with the catch clause of a try statement.

A method that throws an unchecked exception

public double calculateFutureValue(double monthlyPayment,
        double monthlyInterestRate, int months)
{
    if (monthlyPayment <= 0)
        throw new IllegalArgumentException(
            "Monthly payment must be > 0");
    if (monthlyInterestRate <= 0)
        throw new IllegalArgumentException(
            "Interest rate must be > 0");
    if (months <= 0)
        throw new IllegalArgumentException(
            "Months must be > 0");
        // code to calculate and return future value
        // goes here
}

Code that throws an IOException for testing purposes

try
{
    throw new IOException();   // must be the last statement in the try block
}
catch (IOException e)
{
    // code to handle IOException goes here
}

Code that rethrows an exception

try
{
    // code that throws IOException goes here
}
catch (IOException e)
{
    System.out.println("IOException thrown in getFileLength method.");
    throw e;
}
Previous | Try statement | Finally clause | Throws clause | Throw statement | Throwable class | Next