Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java Language
Expertise: Beginner
Jul 27, 1998



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Mandatory exception handling

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?

Although Java makes it easier to write robust programs 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.

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date