Learnitweb

Can we have an empty catch block?

It is legal to have an empty catch block. If we have empty catch block then nothing happens. Empty catch block is something like silently ignoring the exception without doing anything and informing anyone. Which is a bad idea. Generally we do the following in catch blocks:

  • Inform the user about the exception.
  • Log the exception for debugging purposes and future reference.
  • Send an email describing the exception.

It all depends on the issue and workflow what to do if an exceptions occurs. catch block can be used to rethrow the exceptions as well. If we choose to keep catch block empty then it means we decided to do nothing.

If you deliberately decide to keep empty catch block, put at least a comment why you decided to do so.

Following example shows that it is legal to have empty catch block.

import java.io.FileNotFoundException;

public class EmptyCatchBlockExample {

	public static void main(String[] args){
		System.out.println("main method started");
		try {
			throw new FileNotFoundException();
		} catch(FileNotFoundException e) {
			
		}
		System.out.println("after catch block");
		
	}
}

Output

main method started
after catch block