devxlogo

Mandatory exception handling

Mandatory exception handling

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.

See also  Essential Measures for Safeguarding Your Digital Data
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist