
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can We Have an Empty Catch Block in Java?
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
Advertisements