I have read the bug detectors in findbugs website, http://findbugs.sourceforge.net/bugDescriptions.html
I want to write a test code and use Findbugs to detect the REC error.
But the findbugs cannot. Why? Could you help me to solve this?
Thanks,
Below is the description in Findbugs.
REC: Exception is caught when Exception is not thrown (REC_CATCH_EXCEPTION)
This method uses a try-catch block that catches Exception objects, but Exception is not thrown within the try block, and RuntimeException is not explicitly caught. It is a common bug pattern to say try { ... } catch (Exception e) { something } as a shorthand for catching a number of types of exception each of whose catch blocks is identical, but this construct also accidentally catches RuntimeException as well, masking potential bugs.
A better approach is to either explicitly catch the specific exceptions that are thrown, or to explicitly catch RuntimeException exception, rethrow it, and then catch all non-Runtime Exceptions, as shown below:
try {
...
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
... deal with all non-runtime exceptions ...
}
My code is:
public static void test1(){
int A[] = {1,2,3};
int result = 5/0;//divided by 0
int arrOut = A[0]+A[4];//index out of bound
System.out.println(arrOut);
System.out.println(result);
try {
} catch (RuntimeException e) {
// TODO: handle exception
System.out.println("Runtimeex throw");
throw e;
} catch (Exception e) {
// TODO: handle exception
System.out.println("An try error occurred: 0 cannot be divided");
}
}
The try is where the exception occur that you want to catch. However, since it is occurring out of the try block, the exception is not caught by the catch part, which is why FindBugs reporting it as a useless try {...} catch {...} code. The proper code should be as follows.
int A[] = {1,2,3};
try {
int result = 5/0;//divided by 0
int arrOut = A[0]+A[4];//index out of bound
System.out.println(arrOut);
System.out.println(result);
} catch (RuntimeException e) {
// TODO: handle exception
System.out.println("Runtimeex throw");
throw e;
} catch (Exception e) {
// TODO: handle exception
System.out.println("An try error occurred: 0 cannot be divided");
}
}
Related
class Test {
public static void main(String[] args) {
try {
String s = "5.6";
Integer.parseInt(s); // Cause a NumberFormatException
int i = 0;
int y = 2 / i;
}
catch (Exception ex) {
System.out.println("NumberFormatException");
}
catch (RuntimeException ex) {
System.out.println("RuntimeException");
}
}
}
The correct answer is that the program has a compilation error. I thought that the catch (Exception ex) would catch all exceptions including NumberFormatException, that it was a general exception that caught them all?
The block:
catch (Exception ex) {
System.out.println("NumberFormatException");
}
will catch all the exceptions, as the Exception class is the base class for all the exceptions.
When you catch Exception, you catch all the exceptions that extend Exception, which, all the exceptions do. Hence it produces the error that RuntimeException has already been caught
I have been using Find Bugs in Eclipse and I can not figure out why some of the bugs are coming up or how to fix them. Any ideas or help would be great!
The first bug is (Bug: Exception is caught when Exception is not thrown in banking.primitive.core.ServerSolution.saveAccounts()):
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
The second bug is (Bug: Exception is caught when Exception is not thrown in banking.primitive.core.ServerSolution.saveAccounts()):
out.writeObject(accountMap.get(i));
I tried to change it to :
out.writeObject(accountMap.get(Integer.toString(i)));
The third bug is (Bug: Exception is caught when Exception is not thrown in banking.primitive.core.ServerSolution.saveAccounts()):
} catch (Exception e) {
e.printStackTrace();
throw new IOException("Could not write file:" + fileName);
For the first bug this is with my try block as well. I am lost. I tried to follow you post below, but I am confused. Sorry, I am very new!
public ServerSolution() {
accountMap = new HashMap<String,Account>();
File file = new File(fileName);
ObjectInputStream in = null;
try {
if (file.exists()) {
System.out.println("Reading from file " + fileName + "...");
in = new ObjectInputStream(new FileInputStream(file));
Integer sizeI = (Integer) in.readObject();
int size = sizeI.intValue();
for (int i=0; i < size; i++) {
Account acc = (Account) in.readObject();
//CST316 TASK 1 CHECKSTYLE FIX
if (acc != null) {
accountMap.put(acc.getName(), acc);
}
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
See FindBugs Bug Description:
This method uses a try-catch block that catches Exception objects, but Exception is not thrown within the try block, and RuntimeException is not explicitly caught. It is a common bug pattern to say try { ... } catch (Exception e) { something } as a shorthand for catching a number of types of exception each of whose catch blocks is identical, but this construct also accidentally catches RuntimeException as well, masking potential bugs.
A better approach is to either explicitly catch the specific exceptions that are thrown, or to explicitly catch RuntimeException exception, rethrow it, and then catch all non-Runtime Exceptions, as shown below:
try {
...
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
... deal with all non-runtime exceptions ...
}
I am implementing exception handling in java with multiple exceptions.
Look at the following scenario:
Function f1 throws Exceptions e1, e2, e3 and e4
and Function f2 catches these.
Now I want to catch e1,e2 explicitly by catch(Exception e1 and e2) and the other exceptions should be caught all in the same block by catch(Exception e)
So e1 and e2 are a special case, and others are all general exceptions.
So will the following work?
try{
//some work`
} catch(ExceptionType1 e1) {
//do some special logging
} catch (ExceptionType2 e2) {
//do some special logging
} catch(Exception e) {
//do general logging for other exceptions
}
My question is whether ExceptionType1(e1) will also be caught by Exception e?
The Spec writes:
If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:
If the run-time type of V is assignment compatible with (ยง5.2) a catchable exception class of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed, and then there is a choice:
If that block completes normally, then the try statement completes normally.
If that block completes abruptly for any reason, then the try statement completes abruptly for the same reason.
Therefore, at most one catch block will be executed.
For that to work you need to have catch blocks with different Exceptions
like NullPointerException NumberFormatException and the general exception will be caught by catch block with Exception parameter since Exception is the super class of all Exceptions
try{
//some work`
} catch(NullPointerException e1) {
//do some special logging
} catch (NumberFormatException e2) {
//do some special logging
} catch(Exception e) {
//do general logging for other exceptions
}
Using your code will catch all Exceptions in catch(Exception e1){...}
The other catch-blocks are unused. If you want to handle different Exception-types on different way you have to give the catch(...) other Exception-types.
Like
try{
}catch(IOException e1){
// Do sth
}
catch(NullPointerException e2){
// Do sth else
}
// and so on...
You cannot have multiple catch blocks with the same class i.e. Exception
If you have multiple Exceptions you need to create a separate class for each one and make your catch block for a specific class
Just be aware the order of your catch block must go from the more specific to the more generic class
e.g.
try {
} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
} catch (Exception e) {
System.err.println("Caught Exception: " + e.getMessage());
} catch (Throwable e) {
System.err.println("Caught Throwable: " + e.getMessage());
}
So in the above code if the exception is of FileNotFoundException only the first catch will be executed. Otherwise the catch block with Exception is going to be executed for any instance of Exception class that was not caught in the previous catch blocks
At the end Throwable will catch anything that does not inherent from Exception such as Error
In Java, if a general exception is caught and rethrown, will outer methods still be able to catch specific exceptions?
In other words, can I do this:
try {
try {
//...
} catch (Exception e) {
//...
throw e;
}
} catch (SpecificException e) {
//...
}
re-throwing an exception does not change anything about it (it's still the same object originally thrown).
While jtahlborn answer is correct, there is one more appreciation: the compiler will see that you are throwing an exception of the generic type (even if at runtime it can be only of the specific class) and will force you to declare the generic exception in the method header.
private void test() throws FileNotFoundException {
try {
throw new FileNotFoundException("Es una exception");
} catch (IOException e) {
throw e; <-- Error because the method only throws
FileNotFoundException, not IOException
}
}
e is indeed FileNotFoundException, but as it is declared as IOException the compiler works with the broader class. What you can do is "cast" the exception.
throw (FileNotFoundException) e;
Eclipse marks the "throw e" in the inner catch as an unhandled exception, BUT it does catch the exception because when I run this it prints "It worked!". Thanks #jtahlborn. Unfortunately this means that there will still need to be an unnecessary try/catch block somewhere.
public class Tester {
public static void main(String[] args) {
try {
try {
throw new SpecificException("Test!");
} catch (Exception e) {
throw e;
}
} catch (SpecificException e) {
System.out.println("It worked!");
}
}
}
I am using a try catch block to catch an exception. The console shows that it is throwing a null value. But it is not going to the catch block.
try {
System.out.println("Exception here "+SomeObject.getValue());
} catch (NullPointerException e) {
// TODO: handle exception
SomeObject so = new SomeObject();
}
SomeObject.setValue();
}
How could this be handled. Can I also use method level throws NullPointerException ?
It indeed would have went inside the catch block. There is another potential NullPointerException at the line (assuming you are trying to say)
so.setValue();
Having said that it is not advised to throw RuntimeException. It is better you handle NullPointerException in your code not through try/catch but through simple condition checks
it is a bad idea to catch UnChecked Exceptions, rather than catching NullPointerExcetpion, you can simple check for null values in an If condition.
if(SomeObject.getValue()!=null)
System.out.println(SomeObject.getValue());
You can put another try block inside catch
try {
doSomething();
} catch (IOException) {
try {
doSomething();
} catch (IOException e) {
throw new ApplicationException("Failed twice at doSomething" +
e.toString());
}
} catch (Exception e) {
}