Can we have an empty catch block in Java?

JavaObject Oriented ProgrammingProgramming

Yes, we can have an empty catch block. But this is a bad practice to implement in Java.

Generally, the try block has the code which is capable of producing exceptions, if anything wrong in the try block, for instance, divide by zero, file not found, etc. It will generate an exception that is caught by the catch block. The catch block catches and handles the exception. If the catch block is empty then we will have no idea what went wrong within our code.

Example

public class EmptyCatchBlockTest {
   public static void main(String[] args) {
      try {
         int a = 4, b = 0;
         int c = a/b;
      } catch(ArithmeticException ae) {
         // An empty catch block
      }
   }
}

In the above code, the catch block catches the exception but doesn’t print anything in the console. This makes the user think that there is no exception in the code. So it's a good practice to print corresponding exception messages in the catch block.

Output

// An empty catch block
raja
Published on 30-Aug-2019 14:38:58
Advertisements