Java Reference
In-Depth Information
In other words, checked exceptions cannot be ignored. You must write code to either
catch and handle a checked exception, or declare that you are not catching the exception,
which means it must be handled by some other method down the call stack. Either way,
eventually a checked exception must be handled.
The throws Keyword
A method uses the throws keyword to declare that it might throw an exception. For
example, the following method named readFromFile declares that it might throw a
java.io.IOException :
public void readFromFile(String fileName) throws IOException {
FileReader fis = new FileReader(fileName);
System.out.println(fileName + “ was found”);
char data = (char) fis.read();
System.out.println(“Just read: “ + data);
System.out.println(“End of readFromFile”);
}
Because IOException is a checked exception, any method that invokes readFromFile
must either handle or declare the IOException .
Why Not Catch Errors or Runtime Exceptions?
Checked exceptions must be handled or declared, while errors and runtime exceptions
can be ignored. This does not imply that you cannot try to catch an error or exception.
You can try to catch any object of type Throwable , which includes errors and runtime
exceptions.
However, catching an error is often pointless because recovering from an error is diffi cult
and often impossible. On the other hand, you could catch a runtime exception and
recover from the problem, but in general this is considered poor programming design.
Believe it or not, the preferred technique for runtime exceptions is to let them crash your
program, because, in general, runtime exceptions can be avoided with better code. For
example, if a NullPointerException occurs at runtime, modify your code so that it tests
the corresponding reference for null before trying to use it.
Be glad that errors and runtime exceptions do not need to handled or declared. They can
occur in so many situations that if you had to handle or declare them, you would quickly
become irritated with Java!
Search WWH ::




Custom Search