Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find empty catch blocks in Java code

Tags:

java

Is there any way to find all the empty catch blocks inside Java code? I know there are some tools like PMD to do that, but I am using RSA. Is there any way we can write a regex to search for empty catch blocks?

I am working on a corporate machine, where I can't install new software.

like image 313
micheal Avatar asked Nov 24 '09 11:11

micheal


People also ask

Can a catch block be empty 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.

What if try block is empty?

try block will work fine if nothing is in it . You cannot use any checked exception in a catch block if it is never thrown. so with the empty try block u can use catch with unchecked exceptions if exception is thrown or not but u can use checked exception only if it is thrown.

What are try and catch in Java?

Java try and catchThe try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.


2 Answers

You can use this regular expression:

catch\s*\([^\)]*\)\s*\{((/\*(.|[\r\n])*?\*/)|\s)*\}

Where this sub-expression, found in Stephen Ostermiller's website, matches any Java comment:

/\*(.|[\r\n])*?\*/
like image 147
Paolo Fulgoni Avatar answered Oct 16 '22 09:10

Paolo Fulgoni


The Eclipse Java compiler can be configured to produce warnings (or error message) for empty statements:

Java > Compiler > Errors/Warnings > Empty statement.

You could use the batch compiler (Running the batch compiler) if you do not use eclipse.

But then you could use other Java tools as well. Using a Java library is not a sofware installation. As long as the JRE is not locked by the security manager configuration this should always work.

like image 41
Thomas Jung Avatar answered Oct 16 '22 08:10

Thomas Jung