Intellij Structural Search: How to find empty try catch blocks? - java

How can i find the empty try catch blocks?
Using the Copy existing template... I found the structural search for try catch:
try {
$TryStatement$;
} catch($ExceptionType$ $Exception$) {
$CatchStatement$;
}
I want to enhance it so that it does only find try catches with empty catch blocks
It should find:
try {
assertTrue(output.validate());
} catch (Exception e) {
//TODO something
}
or
try {
assertTrue(output.validate());
} catch (Exception e) {
}
or
try {
assertTrue(output.validate());
} catch (Exception e) {}
However not:
try {
assertTrue(output.validate());
} catch (Exception e) {
e.printStackTrace();
}
Right now it obviously finds both since there's no differentiation betweens.
How can I add this extra check?

Use the template you have found and on CatchStatement variable set Min count and Max count to 0.

Related

Can you use multiple catch with same exception

public function() {
try {
// execute code and if error jump into 1st catch
return output;
} catch (Exception e){
//execute code and if error jump in 2nd catch
return output1
} catch (Exception e){
//execute code and stop
return output 2
}
}
The Above is the Code flow I want to achieve, I wanted to check if there is way or better way to do my scenario where I want to try a piece of code and if it fails, catch and execute first catch piece of code and if it again fails and exception occurs in first catch also go for final piece of code in last catch. Any help is very much appreciated. Thanks in advance.
Here is the flow I want to achieve :
try ----if error/exception----> catch1 ----if error/exception----> catch2
You can't do that. To catch a exception inside a catch block you should user another try/catch.
public function() {
try {
return output;
} catch (Exception e){
try {
return output1;
} catch (Exception e2) {
return output2;
}
}
}

IF inside try block

I want to execute my method callmethod if the condition inside the IF statement is met. Else it should execute the catch block. But during implementation, if the condition is not met, it does not go to the catch block.
try{
if(count==0)
callmethod();
}
catch (Exception e){
System.out.println(e);
}
This is a good application for methods:
try {
if (count == 0) {
callOneMethod();
}
else {
callOtherMethod();
}
catch (Exception e) {
callOtherMethod();
}
That way you don't have any duplicated code and you're not doing weird things with exceptions in non-exceptional cases.
Since you are trying to hit the catch block, you need to throw an exception if your parameter is not met (i.e. count != 0).
Example:
try {
if(count==0){
callmethod();
} else {
throw new SomeException("some message");
}
}
catch (Exception e){
System.out.println(e);
}

Multiple Catch blocks vs Catching in Base Exception class

Assuming we are talking about all the exceptions that extends base Exception class,
is:
try {
some code;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
catch (MyOwnException e)
{
e.printStackTrace();
}
same as:
try {
some code;
}
catch (Exception e) {
e.printStackTrace();
}
I am wondering in which case I MUST use the former one?
In the 2nd option Exception will catch all exception, not only those explicitly listed in the first option.
Use the 1st option if you want to catch only selected exceptions, and respond differently to each.
If you want to catch only selected exceptions, and have the same response to all of them, you could use:
catch (InterruptedException | ExecutionException | MyOwnException e)
{
e.printStackTrace();
}
It is good practice to use Exception sub classes rather than Exception class. If you use Exception then it would be difficult to debug.
Here is a link for reference
http://howtodoinjava.com/best-practices/java-exception-handling-best-practices/#3
If you have multiple exceptions which all are extending from...we'll say IndexOutOfBoundsException, then unless you specifically want to print a different message for StringIndexOutOfBoundsException or another sub-class you should catch an IndexOutOfBoundsException. On the other hand if you have multiple exceptions extending from the Exception class, it is proper format to create a multi-catch statement at least in JDK 1.8:
try {
// Stuff
}catch(InterruptedException | ClassNotFoundException | IOException ex) {
ex.printStackTrace();
}
The former one where you create multiple catch statements is if you were trying to do what I said before.
try {
// Stuff
}catch(StringIndexOutOfBoundsException se) {
System.err.println("String index out of bounds!");
}catch(ArrayIndexOutOfBoundsException ae) {
System.err.println("Array index out of bounds!");
}catch(IndexOutOfBoundsException e) {
System.err.println("Index out of bounds!");
}

Get exception instance class name

I would like to know what the exception instance was in this situation:
try {
// some risky actions
} catch (Exception e) {
System.out.println("Get instance name there");
}
How can I achieve this?
Here you go:
try {
throw new ArithmeticException();
} catch (Exception e) {
System.out.println( e.getClass().getCanonicalName());
}
Output:
java.lang.ArithmeticException
The type of the exception is shown as part of the output of:
e.printStackTrace();
To get it programmatically you can use:
String exceptionClassName = e.getClass().getName();
It is poor form to have logic depending on exception sub types within a catch block. Sonar will flag this as a code violation (squid S1193).
Instead you should add multiple catch blocks to catch different types of exceptions:
try {
readFile(fileName);
}
catch (java.io.IOException e) {
LOG.error("Error accessing file {}", fileName, e);
}
catch (java.lang.IllegalArgumentException e) {
LOG.error("Invalid file name {}", fileName, e);
}
Note: Since Log4j 2 (and SLF4J 1.6+) you can add a throwable as the last parameter and it will be recognized as such. So the above will work!
Since Java 7 you can also do a multi-catch:
}
catch (java.io.IOException | java.lang.IllegalArgumentException e) {
LOG.error("Could not read the file {}", fileName, e);
}
The benefit of the multi-catch is that you can handle multiple exception types within a single catch block without having to revert to a common super class (like java.lang.Exception) that would include exception types you didn't want to handle.
Default exception logging is something like
try
{
//
}
catch (Exception e)
{
e.printStackTrace();
}
This will print the stacktrace of the exception to system.err
If you are looking to add some contextual information, you can take a look at Apache Commons ContextedRuntimeException
public static void main(String[] args) {
try {
doSomething();
} catch (ContextedRuntimeException e) {
System.out.println(e.getMessage());
System.out.println(e.getContextEntries());
}
}
private static void doSomething() {
int divisor = 0;
int dividend = 100;
int result;
try {
result = dividend / divisor; // Just throw an exception to test things....
System.out.print("DIVISION RESULT: "+result);
} catch (ArithmeticException e) {
throw new ContextedRuntimeException("Oops..division by zero not allowed", e)
.addContextValue("Divisor", divisor)
.addContextValue("Dividend", dividend);
}
}
would output:
Oops..division by zero not allowed
Exception Context:
[1:Divisor=0]
[2:Dividend=100]
---------------------------------
[(Divisor,0), (Dividend,100)]

Catch the same exception twice

I have the following:
public void method(){
try {
methodThrowingIllegalArgumentException();
return;
} catch (IllegalArgumentException e) {
anotherMethodThrowingIllegalArgumentException();
return;
} catch (IllegalArgumentException eee){ //1
//do some
return;
} catch (SomeAnotherException ee) {
return;
}
}
Java does not allow us to catch the exception twice, so we got compile-rime error at //1. But I need to do exactly what I try to do:
try the methodThrowingIllegalArgumentException() method first and if it fails with IAE, try anotherMethodThrowingIllegalArgumentException();, if it fails with IAE too, do some and return. If it fails with SomeAnotherException just return.
How can I do that?
If the anotherMethodThrowingIllegalArgumentException() call inside the catch block may throw an exception it should be caught there, not as part of the "top level" try statement:
public void method(){
try{
methodThrowingIllegalArgumentException();
return;
catch (IllegalArgumentException e) {
try {
anotherMethodThrowingIllegalArgumentException();
return;
} catch(IllegalArgumentException eee){
//do some
return;
}
} catch (SomeAnotherException ee){
return;
}
}

Categories

Resources