Question:
Why should some of the statements that might throw an exception be in try/catch block (otherwise the compiler reports a syntax error), and some need not be, even though they might throw an exception?
Answer:
Although Java makes it easier to write robustprograms by providing compiler-enforced exception handling, Java also provides a means to bypass this feature. All exceptions derived from java.lang.RuntimeException
do not have to be explicitly caught for a Java program to compile. If such an exception is thrown at runtime without being caught, your Java program will terminate and print a stack trace to standard output.
This behavior also applies to Error
instances, which in most cases should not be caught. Any method that throws a Throwable
instance derived from Error
or RuntimeException
does not have to list the Throwable
in its throws
clause. These conditions also do not have to be caught in a try/catch block. As a consequence, you do have keep a close eye on what exceptions you might want to catch that you are not forced to catch. For example, there are many times when you might want to catch an ArrayIndexOutOfBoundsException
and recover gracefully instead of letting your program die. This particular exception is derived from RuntimeException
so that every time you access an array an array element you aren’t forced to catch an exception.