Exceptions
Objective #1: Explain the difference between compile errors and run-time
errors.
- A compile error occurs when the Java compiler (j2sdk) and/or Eclipse finds a misspelled
keyword, a misplaced operator such as a semicolon, or similar typing mistake.
- A run-time error occurs when the user enters a value that causes division
by zero, the Java Virtual Machine (JVM) promotes or casts an object incorrectly,
or another problem occurs while the program is executing. This type of run-time error is often called an exception error (even though it's an exception object that is being "thrown").
Objective #2: Understand the underlying causes of several kinds of
exception errors.
- On the AP Exam, you are responsible for understanding the following types
of run-time exceptions:
- ArithmeticException -
thrown when an illegal arithmetic operation has occurred (e.g. division
by zero). A tricky exception to this is that when an arithmetic operation
with data type double occurs, Java doesn't throw an exception.
- ArrayIndexOutOfBoundsException -
thrown when programmer attempts to access an array index position
that doesn't exist
- IndexOutOfBoundsException -
this is the parent class of ArrayIndexOutOfBoundsException and is thrown
when an attempt to access a non-existent index position of an ArrayList is made
- NullPointerException -
thrown when an attempt to use a method is made on an object variable
that is equal to null and has not been
instantiated (e.g. the code segment Student
john = null; john.computeGrade(); would
cause this exception to be thrown since john has
not been instantiated with the new operator so you can't compute his grade
yet.)
- IllegalArgumentException -
thrown when a method is passed an illegal or inappropriate argument (e.g.
if you wrote a Student class, you could
throw an IllegalArgumentException object
from within a constructor that attempts to give a student a name that
starts with a numerical digit). This exception is usually not tested on the AP exam.
The following are not covered on the AP exam or unit tests.
Objective #3: Understand a variety of
exception errors that may not be covered on the AP exam.
- StringIndexOutOfBoundsException -
similar to ArrayIndexOutOfBoundsException except
it is thrown specifically when an attempt is made to access a non-existent
character of a string object (e.g. System.out.println("wyomissing".charAt(-2)); )
- ClassCastException -
thrown when an attempt to cast an object to a subclass or other class
of which it is not an instance (e.g. you can't cast a Pencil object
to a Walrus object)
- IllegalStateException -
thrown when a class invariant is violated and an object takes on an incorrect
property value or when a method is executed on an object at an illogical
time (e.g. if a class invariant of a Student class
is that a student object will never have a negative grade point average
then a mathematical operation that causes the student's GPA to be negative
will throw this kind of exception). This exception is usually not tested on the AP exam.
Objective #4: Throw and catch exceptions where appropriate.
- Java provides a way for programmers to anticipate
the possibility of certain kinds of run-time errors through exception-handling.
A programmer, in anticipation
of a possible run-time error, can write code that will "throw
an exception" if
a run-time error occurs in a given code segment.
- Actually, an exception is an object from an exception
class. "Throwing
the exception" amounts to ending the execution of a method prematurely
when an error occurs and sending (i.e. throwing) an exception object back
to the method that called the method where the run-time error occurred. This
is done with the keyword throw rather than the keyword return.
- When running the program where an exception is thrown due to a run-time
error, the program ends with an error message like this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
at Ch14Demo1.main(Ch14Demo1.java:5)
which means that an error occurred on line 5 of the main method in the class
named Ch14Demo1. An ArrayIndexOutOfBoundsException object was thrown. This
means that the programmer tried to access an element in an array that doesn't
exist. For example, if the array has a size of 10 and a programmer tried
to display or overwrite the value in the element with index position 10 this
kind of exception will be thrown. The Sun programmers who created the Array
class have a throw statement somewhere in the Array class that throws this
exception object and error message.
- There is a difference between checked and unchecked
exceptions. With checked exceptions you are required
to use a throws clause. You are not
required to use a throws clause with unchecked exceptions. Checked exceptions
often occur no matter how well you try to prevent them. They are often
the result
of
something that the user does which is out of your control as the programmer.
Unchecked exceptions are things that you can prevent with careful logic
and if statements. Unchecked exceptions are runtime exceptions while checked
exceptions are checked by the compiler. All of the exceptions explained
below are unchecked exceptions. AP students are
not responsible for understanding, interpreting, or throwing checked exceptions.
- Your code does not need to explicitly throw an ArithmeticException, NullPointerException, ClassCastException, or ArrayIndexOutOfBoundsException since Java automatically throws those exceptions when the condition is triggered.
- The following BankAccount class
constructor throws an IllegalStateException object
if an attempt to store a negative balance in a bank account is made:
public BankAccount(double initialBalance)
{
if (initialBalance < 0)
{
throw new IllegalArgumentException("Initial
balance must be non-negative.");
}
balance = initialBalance;
}
The throw statement
acts like a return statement.
The method ends when it reaches a throw statement. Note that the IllegalArgumentException object being thrown is an anonymous object.
- The following BankAccount withdraw method throws an IllegalStateException object if an attempt to make the balance of the account negative is made.
public void withdraw(int amount)
{
if (balance - amount < 0)
{
throw new IllegalStateException("Balance cannot be negative.");
}
balance -= amount;
}
- To catch an exception, you use a try/catch/finally statement. While you do not have to write any try/catch/finally statements on the AP exam, it is good to know how to use this structure to make client programs more robust.
The following code segment would handle the exception thrown by the constructor above.
// user inputs values for userBalance & userAmount
try
{
BankAccount savings = new BankAccount(userBalance);
savings.withdraw(userAmount);
}
catch (IllegalStateException exception)
{
System.out.println(exception);
}
catch (IllegalArgumentException exception)
{
System.out.println(exception);
}
finally
{
System.exit(0);
}
The code in the finally clause is guaranteed to execute even if an exception is thrown from the code in the try clause and whether the exception is caught by one of the catch handlers or not.