Yes we can have an empty catch block. But implementing this in Java is a bad practice.
Generally speaking, try block has code that can generate an exception if any error occurs in the try block, such as division by zero, file not found, etc.. It will generate an Exception and be caught by the catch block. The catch block catches and handles the exception. If the catch block is empty, then we won't know what went wrong in the code.public class EmptyCatchBlockTest { public static void main(String[] args) { try { int a = 4, b = 0; int c = a/b; } catch(ArithmeticException<strong> </strong>ae) { // An empty catch block } } }
In the above code, the catch block catches the exception but does not print anything in the console. This makes the user think that the code is not abnormal. Therefore, it is better to print the corresponding exception message in the catch block.
// An empty catch block
The above is the detailed content of In Java, can we use empty catch block?. For more information, please follow other related articles on the PHP Chinese website!