Avoid Empty Exception Handlers

Avoid Empty Exception Handlers

One of the most frustrating experiences when running a Java program is an empty line where you expect information about a thrown exception. The programmer probably meant to catch the exception but did nothing with it. As a result, when the exception is thrown at run time, there is no way to indicate to the user that it was thrown, which leads to erroneous results. For example, consider a method called method1 that throws an exception.

 1. private void method1 () throws Exception {2.   // Do stuff3.   throw new Exception();4. }

Now consider this code:

 1.     System.out.println("Start");2. 	  3.     try {4.       method1();5.     }6.     catch (Exception e) {7.       // EMPTY EXCEPTION HANDLER8.     }9.     System.out.println("End OK");

You catch the exception on Line 6. However, the program does nothing with the exception. The result is that at run time, there is no trace of the exception; it becomes nonexistent. The output of the code excerpt is:

 StartEnd OK

Therefore, you should avoid empty exception handlers as good programming practice.

See also  How IoT Tech Will Transform Logistics

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