Unreachable catch block: Unreachable catch block for InvalidFormatException - java

I am facing problem while reading data from .xlsx file as the catch (InvalidFormatException e) return error for exception as "Unreachable catch block for InvalidFormatException. This exception is never thrown from the try statement body"
I have used openxml4j import which I think is necessary
public static Object[][] getTestData(String sheetname) {
FileInputStream file = null;
try {
file = new FileInputStream(TEST_DATA_SHEET_PATH);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
book = WorkbookFactory.create(file);
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
It is expected that there should not be error for the InvalidFormatException and data should be red from .xlsx file

try {
book = WorkbookFactory.create(file);
} catch (InvalidFormatException e) {
e.printStackTrace();
}
The code inside this try block, does not throw an InvalidFormatException. That is why you are getting the error message.
Perhaps your intention is using that catch block somewhere else.
From the documnetation:
https://poi.apache.org/apidocs/dev/org/apache/poi/ss/usermodel/WorkbookFactory.html#create-java.io.File-
This is the methods signiture:
public static Workbook create(java.io.File file)
throws java.io.IOException,
EncryptedDocumentException
As you can see above, no InvalidFormatExceptionis thrown from this method.

This happens if the IDE can't see or understand that a specific ( InvalidFormatException ) exception is thrown in a given code segment.
You can simply solve this problem by joining you try blocks:
try {
book = WorkbookFactory.create(file);
} catch (Exception e) {
e.printStackTrace();
}
with this approach you can also could clean up and join your code like this if your error handling allows it:
try {
file = new FileInputStream(TEST_DATA_SHEET_PATH);
book = WorkbookFactory.create(file);
} catch (Exception e) {
e.printStackTrace();
}

Related

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

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.

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;
}
}

How do I avoid Sonar's "preserve stack trace" violation?

Sonar gives a major violation error ("Preserve Stack Trace") for the following code. Following method is used to throw an exception. What are the steps should I take to overcome this violation?
public void exceptionHandler(String exception) throws PhDashException {
String exceptionMsg = exception.replaceAll("-", "_");
ExceptionPhDash pHDashExceptionMapper = new ExceptionPhDash();
try {
pHDashExceptionMapper = new ObjectMapper().readValue(exceptionMsg, ExceptionPhDash.class);
} catch (JsonParseException e) {
LOGGER.info(e.getMessage());
} catch (JsonMappingException e) {
LOGGER.info(e.getMessage());
} catch (IOException e) {
LOGGER.info(e.getMessage());
}
throw new PhDashException(pHDashExceptionMapper.getMessage());
}
You've logged each exception; that should be enough as far as preserving information is concerned like below,
LOGGER.info("Unexpected Exception has occurred", e);
Or You should re throw the PhDashException if you can, because, you should be enough as far as preserving information is concerned
throw new PhDashException(pHDashExceptionMapper);

Java Exception inside catch block

here is a code:
try {
FileOutputStream fout=new FileOutputStream("path");
javaClassFun(url,fout);
fout.close();
} catch (MalformedURLException ex) {
System.err.println("Invalid URL"+ex);
} catch (IOException e) {
System.err.println("Input/Output error"+e);
}
when i cut the last catch block and paste it after try block it gives unreachable catch block error.
I want to know what is the reason behind this.
The reason why is that MalformedURLException inherits from IOException.
try {
//call some methods that throw IOException's
} catch (IOException e) {
// This will catch MalformedURLException since it is an IOException
} catch (MalformedURLExceptionn ex) {
// Will now never be caught! Ah!
}
If you want to design catch blocks which properly handle an exception hierarchy, you need to put the super class last and the subclasses which you want to handle individually prior to it. See the example below for how to handle the IOException class hierarchy as it pertains to your code.
try {
//call some methods that throw IOException's
} catch (MalformedURLExceptionn ex) {
// This will catch MalformedURLException
} catch (IOException e) {
// This will catch IOException and all other subclasses besides MalformedURLException
}

Categories

Resources