Sub topic 10
Handle and Declare Exceptions
A method cannot always finish its work. A number may be in the wrong format, or a file may be unavailable. In Java, a method can signal a problem by throwing an exception. An exception is an object that describes a problem during a program’s run.
A method’s contract is what callers can expect from it. The contract includes the result on success and the exceptions the method may report. A caller can handle a problem, or sometimes let its own caller handle it.
How exceptions move between methods
When a statement throws an exception, the method stops its normal work. Java looks for a matching handler: code that can respond to that kind of exception. If the method has no matching handler, the exception moves to its caller. This continues until a handler is found or the program stops.
If no code handles an exception, Java prints a stack trace and the program may stop. A stack trace is a list of method calls that helps show where the problem happened.
Checked and unchecked exceptions
Java treats exceptions in two main ways.
- A checked exception is an exception the Java compiler requires you to handle or declare. The compiler is the tool that checks your code and turns it into a program Java can run.
IOException, which can report a problem reading data, is a checked exception. - An unchecked exception is an exception the compiler does not require you to handle or declare.
NumberFormatException, which can report text that is not a valid number, is an unchecked exception.
Unchecked exceptions are of type RuntimeException or a type based on it. For example, NumberFormatException is a kind of RuntimeException. The compiler still checks that the code has valid syntax; it just does not require a handler or a declaration for these exceptions.
Java also has Error types for serious problems, such as running out of memory. Errors are not checked exceptions, and ordinary application code usually should not try to handle them.
Handle an exception with try and catch
A try block contains code that might throw an exception. A catch block says which type of exception it handles and what to do about it.
If an exception occurs in the try block, Java skips the rest of that block. It then looks for a matching catch block. If it finds one, the code in that block runs.
A finally block is optional. It runs after the try block and any matching catch block, whether or not an exception was thrown. It is useful for work that should happen in either case, such as cleanup.
Declare an exception with throws
A method can use throws after its parameter list to declare an exception it may pass to its caller:
static int scoreFromText(String text) throws ScoreExceptionThis says that scoreFromText may pass a ScoreException to its caller. It does not mean the method always throws one. On success, this method can still return an int.
Do not confuse these two words:
throwsappears in a method declaration. It tells callers about an exception.throwappears in a method body. It actually throws an exception object.
For a checked exception, a method must handle it or declare it. A caller that receives the exception faces the same choice.
Worked example: check a score
The following program accepts text and tries to turn it into a score from 0 through 100. It uses a custom checked exception named ScoreException. A custom exception is an exception type defined by the program.
Save this code in a file named ScoreDemo.java:
class ScoreException extends Exception {
ScoreException(String message) {
super(message);
}
ScoreException(String message, Throwable cause) {
super(message, cause);
}
}
class ScoreDemo {
static int parseScore(String text) throws ScoreException {
int score;
try {
score = Integer.parseInt(text);
} catch (NumberFormatException problem) {
throw new ScoreException("Enter a whole number.", problem);
}
if (score < 0 || score > 100) {
throw new ScoreException("Score must be from 0 to 100.");
}
return score;
}
static int scoreFromText(String text) throws ScoreException {
return parseScore(text);
}
public static void main(String[] args) {
String[] inputs = {"72", "oops", "101"};
for (String input : inputs) {
try {
int score = scoreFromText(input);
System.out.println(input + " -> " + score);
} catch (ScoreException problem) {
System.out.println(input + " -> " + problem.getMessage());
} finally {
System.out.println("Finished: " + input);
}
}
}
}Run it with the Java compiler and launcher:
javac ScoreDemo.java
java ScoreDemoThe output is:
72 -> 72
Finished: 72
oops -> Enter a whole number.
Finished: oops
101 -> Score must be from 0 to 100.
Finished: 101Follow the successful call
For "72", main calls scoreFromText, which calls parseScore. The Integer.parseInt method converts the text to the integer 72. The score is in range, so parseScore returns it. The value travels back to main, which prints it.
No catch block runs for this input. The finally block still prints Finished: 72.
Follow the failures
For "oops", Integer.parseInt throws a NumberFormatException. The matching catch block in parseScore creates and throws a ScoreException instead.
The original exception is passed as the cause. A cause is an exception that explains why another exception was thrown. Keeping it can help someone investigate the problem later. The message gives the caller a simpler explanation.
For "101", conversion succeeds, but the value is outside the allowed range. The if statement throws a new ScoreException. In both failure cases, parseScore does not reach its return statement.
ScoreException is checked because its declaration uses extends Exception and does not extend RuntimeException. The word extends makes the new type a kind of Exception.
Follow the declaration
parseScore declares throws ScoreException. The method scoreFromText calls it but does not handle that exception, so scoreFromText declares it too.
Finally, main handles ScoreException in its catch block. The variable problem holds the exception object. Calling problem.getMessage() gets the message supplied when the exception was created. The loop can then continue to the next input.
Try removing throws ScoreException from scoreFromText and compiling again. The compiler reports that the checked exception is not handled or declared. Restore the declaration before continuing.
Clean up after a method call
The example uses finally to print a progress message. In real programs, finally can also release something the program is using. For example, a method may need to close a reader, an object that reads text.
finally normally runs even if the try block returns or an exception has no matching handler in that method. It is not an absolute guarantee: for example, it cannot run if the Java process is stopped suddenly. Also, if finally throws its own exception, that can hide an earlier problem.
For many objects that need closing, Java offers try-with-resources. A resource is an object that needs to be closed after use. This form of try closes the resource for you, including when the work throws an exception.
Save this separate program as ReaderDemo.java:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
class ReaderDemo {
public static void main(String[] args) throws IOException {
try (BufferedReader reader =
new BufferedReader(new StringReader("First line\nSecond line"))) {
System.out.println(reader.readLine());
}
}
}Compile and run it:
javac ReaderDemo.java
java ReaderDemoIt prints First line. This example reads from text in the program, so it does not need a file. The reader is closed when the try block ends.
Reading or closing can throw an IOException. Here, main declares that checked exception rather than catching it. If one occurs, Java reports the uncaught exception and the program ends. In a program that can recover, a caller could instead catch it and take an action, such as asking the user to try again.
Choose a clear exception contract
A useful exception contract helps callers decide what to do.
- Describe when a method can fail, not just its successful result. For example, say that a score must be a whole number from 0 to 100.
- Handle an exception where the code can make a useful decision. If a method cannot fix the problem, passing it to its caller may be clearer.
- Give exception messages enough detail to explain the problem. Keep the original cause when changing one exception into another.
- Do not leave a
catchblock empty just to make the compiler happy. That hides the problem and may let the program continue with a wrong result. - Use a checked exception when you want callers to handle or declare a kind of failure. Unchecked exceptions can also be useful, but callers are not forced to address them.
A method can declare more than one exception type by separating the types with commas. Callers must handle or declare each checked type that can reach them.
Practice
Exercise
In the score example, what happens after parseScore receives "101"?
Show answer
It throws a ScoreException. scoreFromText passes it on, main catches it and prints the message, and finally prints the finished message.
Exercise
What is the difference between throw and throws?
Show answer
throw actually throws an exception object. throws declares an exception that a method may pass to its caller.
Exercise
A method calls another method that declares IOException. What must the caller do if it does not catch that exception?
Show answer
The caller must declare IOException with throws so it can pass the checked exception to its own caller.