Java Reference
In-Depth Information
public String getMessage()
This method returns the detail message of the Throwable object. The message is set in
the Throwable constructor.
public String toString()
This method returns a short description of the Throwable object that includes the type of
exception and its message.
You can fi nd examples of printing the stack trace throughout this section. Here is a simple
example to demonstrate the difference between getMessage and toString :
try {
throw new NullPointerException(“Be careful!”);
}catch(NullPointerException e) {
System.out.println(“getMessage: “ + e.getMessage());
System.out.println(“toString: “ + e.toString());
}
The output of this code is
getMessage: Be careful!
toString: java.lang.NullPointerException: Be careful!
Multiple catch Clauses
Let's look at a more realistic example and one that contains multiple catch clauses. The
following MyFileReader class opens a fi le for reading and reads in a single character. The
FileReader constructor invoked on line 6 throws a FileNotFoundException if the specifi ed
fi le cannot be found. Study the code and see if you can determine the output when the fi le is
not found on line 6.
1. import java.io.*;
2.
3. public class MyFileReader {
4. public void readFromFile(String fileName) {
5. try {
6. FileReader fis = new FileReader(fileName);
7. System.out.println(fileName + “ was found”);
Search WWH ::




Custom Search