InterviewSolution
| 1. |
Can we have an empty catch block? |
|
Answer» Yes, we can have an empty catch block in Java. This is a bad practice though and shouldn’t be implemented. Generally, the try block has the code which is capable of producing exceptions. WHENEVER SOMETHING out of the blue or malicious is written in the try block, it generates an exception which is caught by the catch block. The catch block identifies(catches), handles the exceptions and usually prompts the user on what is wrong. If the catch block is empty then you will have no idea what went wrong with your code. Take for example, division by zero when HANDLED by an empty catch block public class Example { public static void MAIN(String[] args) { try { int a=4 ,b=0; int c=a/b; } catch(ArithmeticException E) { } } }The catch block catches the exception but doesn’t print anything. This makes the user think that there is no exception in the code. $javac Example.java $java Example But when the catch block is not empty, it gives a sense of awareness to the user about the exception. public class Example { public static void main(String[] args) { try { int a=4, b=0; int c=a/b; } catch(ArithmeticException e) { System.out.println("Division by zero is illegal"); } } }The output for the following is as follows $javac Example.java $java Example Division by zero is illegal |
|