| Student ____Stephanie_Long_____ Email __stephanielong8@comcast.net____ |
_Exceptions_in_Java_ |
Key point #1: What are Exceptions?
Key point #2: Throwing Exceptions
Key point #3: Catching and Handling Exceptions
Key point #4: Exception Messages
Key point #5: Method Execution and Exceptions
Key point #6: Good Practices when using Exceptions
Exceptions are a way for Java to communicate with a calling method that an abnormal condition has
occured.
There are two types of exceptions in Java:
A Checked Exception and an Unchecked Exception.
A checked exception occurs when the Java compiler and the Java virtual machine check to make sure
a specific rule has been obeyed, but they find that it has been violated, and thus throw an exception. Classes
which derive from Throwable and Exception
classes are considered checked exceptions. Checked exceptions usually indicate invalid
conditions exist outside the program.
For example: invalid user input or absent files
An unchecked exception is an exception which is not checked for by the compiler or the Java virtual machine. Classes
which derive from the RunTimeException class are considered unchecked exceptions.
Unchecked exceptions can indicate there is an error in the logic of the program which cannot be resolved at runtime.
For example: invalid arguments passed to a non-private method
Whether or not an exception is checked or unchecked depends on where it falls in the exception
heirarchy. See diagram below:
|
There are three classes in Java which are used with the creation of Exceptions.
In most cases of exceptions, using the java.lang's existing exceptions will do the job. See the diagram below.
|
If it becomes the case that you need or want to convey more information than which is provided by the given exceptions in the java.lang class, then you can create an exception. Look at this example:
To throw an exception you must simply use the throw keyword with an object reference of type Throwable:
For example:
throw new UnderInflatedException();
A class will throw an exception when it indicates an error in the logic.
Look at this example:
class VirtualAuto {
private static final int tooMuch = 65;
private static final int tooLittle = 15;
public void checkTires(Automobile auto) throws
UnderInflatedException, OverInflatedException {
int pressure = auto.getTireAir();
if (pressure <= tooLittle) {
throw new UnderInflatedException();
}
else if (pressure >= tooMuch) {
throw new OverInflatedException();
}
}
}
class Automobile {
private int airPressure = 35;
public void setpressure(int val) {
airPressure = val;
}
public int checkTires() {
return airPressure;
}
}
Java requires a method to declare the exceptions it can throw. The throws clause of a method
clarifies to programmers what exceptions they may encounter and have to deal with when using the method.
A method can throw multiple exceptions.
Only methods which can cause a program to end abruptly should be included in the throws clause.
If a method catches an exception, the exception should not be declared in the throws message.
class VirtualAuto {
public void checkTires(Automobile auto) throws UnderInflatedException,
TirePressureException {
try {
if (auto.checkTires() < 20) {
throw new UnderInflatedException();
}
else if (auto.checkTires() > 50) {
throw new OverInflatedException();
}
else {
System.out.println("Tire Check Passed");
}
}
}
catch (OverInflatedException e) {
System.out.println("The tires are overinflated.");
}
}
}
If a method calls a second method which can result in exceptions, the first method must use a throws clause identify the exceptions which
are possible from calling the second method, and are not caught by the method.
class VirtualAutoShop {
public static void serveCustomer(VirtualAuto virAuto,
Automobile auto)throws UnderInflatedException {
try {
virAuto.checkTires(auto);
}
catch (TirePressureException e) {
System.out.println("Tire Pressure cannot be read.");
}
}
}
To handle an exception in Java, you must catch it.
Write a try
block, with at least one catch clause.
A catch clause specifies one exception type to handle.
A try block alerts the Java virtual machine that if an exception occurs in
the code within the block, and the catch exception type matches the exception, then
the statement in the catch clause should be executed by the virtual machine.
Look at this example:
class VirtualAutoShop {
public static void serveCustomer(VirtualAuto virAuto,
Automobile auto) {
try {
virAuto.checkTires(auto);
System.out.println("Pressure good.");
}
catch (UnderInflatedException e) {
System.out.println("Pressure too low.");
}
catch (OverInflatedException e) {
System.out.println("Pressure too high.");
}
}
}
It is possible for multiple catch clauses to handle the same exception, so the ordering of the catch
clause examination is important.The first catch
found to handle the exception will get to "catch" it.
A superclass exception must be caught after its subclasses.
There are two basic ways to handle an exception. Those are:
Termination and Resumption
In termination, the exception is considered so critical that there is no way to resume execution, so it causes the method to
terminate.
The alternative, resumption, is when after the exception is caught and handled, execution resumes.
Resumption can make code difficult to write and maintain because an exception can be created at any points in the program.
When you are writing code which handles exceptions and you have some code which you want to have
execute even if an exception occurs (like making sure a file gets closed), you can ensure it gets executed with a
finally clause.
To implement a finally clause:
(1) Enclose the code that has multiple exit points in a try block
(2) place the code that must be executed when the try block is exited in a finally clause.
Look at this example:
class VirtualAutoShop {
public static void serveCustomer(VirtualAuto virAuto,
Automobile auto) {
try {
virAuto.checkTires(auto);
System.out.println("Pressure good.");
}
catch (UnderInflatedException e) {
System.out.println("Pressure too low.");
}
catch (OverInflatedException e) {
System.out.println("Pressure too high.");
}
finally
{
System.out.println("Check tires again");
}
}
}
A try block must have either a finally clause or a
catch clause associated with it. If both a finally
and a catch clause are associated with a try block, the finally must follow the
catch clause(s).
Even if an exception is thrown which is not caught by a catch clause, the
finally clause still gets executed.
The exception class allows you to specify a String message to be initialized when the exception is constructed. To access this message, you can invoke the getMessage() method on the exception.
It is very important to javadoc the exceptions you create.
Look at this example:
/**
* checkTires checks the tire pressure of the customer's car.
*
* @param virAuto the customer to help represented by a car
* @param auto the customer's car
*
* @exception UnderInflatedException if the air pressure is too low in the tires
* @exception OverInflatedException if the air pressure is too high in the tires
*/
public void checkTires(Automobile auto) throws UnderInflatedException,
TirePressureException {
try {
if (auto.checkTires() < 20) {
throw new UnderInflatedException();
}
else if (auto.checkTires() > 50) {
throw new OverInflatedException();
}
else {
System.out.println("Tire Check Passed");
}
}
}
catch (OverInflatedException e) {
System.out.println("The tires are overinflated.");
}
}
}
The code inside try blocks are in a way, surrounded by their corresponding catch blocks. The catch blocks are examined from the inside out if an exception occurs. This being the case, programmers can nest multiple tryblocks within other try blocks which builds up the amount of catch protection surrounding the code. It is possible for a method which is executed within a try block, and the exception is handled by the catch clauses surrounding the code. Meaning an exception can be thrown way before the catch clause to handle it is found in the method invocation stack. This can cause the correct catch clauses to be popped off the stack and the wrong catch could be used to handle the exception.
Avoid empty catch blocks
Javadoc all exceptions
Be specific in the throws clause
Key point #1: What are Exceptions?
Key point #2: Throwing Exceptions
Key point #3: Catching and Handling Exceptions
Key point #4: Exception Messages
Key point #5: Method Execution and Exceptions
Key point #6: Good Practices when using Exceptions
Question #1:
What are the two types of handling an exception in Java?