Java: Poor error handling, Throw inside Finally - java

I have the following code which I am running through fortify. Why it gets marked for poor error handling, throw inside finally?
private String getResourceContent(String fileName) throws IOException {
try (InputStream resource = ErrorResource.classLoader.getResourceAsStream(fileName)) {
return new String(resource.readAllBytes(), StandardCharsets.UTF_8);
} catch (NullPointerException n) {
throw new ErrorDescriptorException(
String.format("Error loading Error description data from Resource file [%s].", fileName), n);
}
}

Explanation
This is explained very well in the official documentation (see Poor Error Handling: Throw Inside Finally). Let me quickly quote the important sections:
Using a throw statement inside a finally block breaks the logical progression through the try-catch-finally.
In Java, finally blocks are always executed after their corresponding try-catch blocks and are often used to free allocated resources, such as file handles or database cursors. Throwing an exception in a finally block can bypass critical cleanup code since normal program execution will be disrupted.
So you can easily bypass cleanup code by doing that, which leads to resource leaks.
Although not directly visible in your code, you actually have a hidden finally block since you are using try-with-resources which automatically closes the resource in a finally block.
Also see Throwing an exception inside finally where this was already discussed.
Example
Here is an example from the official documentation:
public void processTransaction(Connection conn) throws FileNotFoundException {
FileInputStream fis = null;
Statement stmt = null;
try {
stmt = conn.createStatement();
fis = new FileInputStream("badFile.txt");
...
} catch (FileNotFoundException fe) {
log("File not found.");
} catch (SQLException se) {
// handle error
} finally {
if (fis == null) {
// This bypasses cleanup code
throw new FileNotFoundException();
}
if (stmt != null) {
try {
// Not executed if the exception is thrown
stmt.close();
}
catch (SQLException e) {
log(e);
}
}
}
}
The call to stmt.close() is bypassed when the FileNotFoundException is thrown.
Note
Why are you checking for null using a NullPointerException instead of a basic if-else? There is rarely ever a valid reason to catch a NullPointerException. Just do:
try (InputStream resource = ErrorResource.classLoader.getResourceAsStream(fileName)) {
if (resource == null) {
// TODO Throw your exception here
}
return new String(resource.readAllBytes(), StandardCharsets.UTF_8);
}
It might also help to improve the error message by telling the exact reason that the resource could not be found.

Consider the following code, which is loosely based on yours:
String throwing(InputStream inputStream) throws IOException {
try (InputStream resource = inputStream) {
return "good";
} catch (NullPointerException n) {
return "bad";
}
}
You see, no exceptions thrown here. Still, you cannot remove the throws IOException bit – how’s that? Well, InputStream#close() can throw it, and it will be in the implicit finally block that the try-with-resources statement created. I guess there’s not much you can do about it, it looks like a Fortify false positive.

Beyond the misleading message from your tool, there is actually is poor error handling in your code, for multiple of reasons:
catching NPE is really bad practice. Either it is a bug (something that is null and shouldn't), or your code is missing a check if (whatever == null) and the corresponding code to deal with that expected situation
assuming that this NPE has exactly that meaning that you express in your new Exception is well, just guessing
In other words: without further information, it is not clear what exactly your tool complains about. But: one doesn't need a tool to understand: this is poor error handling.
Beyond that, such tools typically give some sort of information about their warnings. Meaning: there might be an "error id" coming with that warning, and you should be able to look up that "error id" in the documentation of your tool for further explanations.

Related

Java 'finally' clause in a nested 'try' block

Will the following finally clause be executed, if an exception is thrown by the PrintWriter?
try{
PrintWriter out = new PrintWriter(filename);
try {
//output
} finally {
out.close();
}
} catch {
//handle exception
}
If the PrintWriter throws an exception, then the nested try block will never get executed, but why the nested finally clause will still be executed, even it's nested and skipped?
Updates:
I ran some tests, if an exception is thrown before the nested try clause, that nested finally will not be executed.
If the exception is thrown inside the nested try clause, then the inner finally and the outter catch will be executed.
No because the inner try block will not be reached when an exception occurs before and therefore the finally block is not reached either.
Finally block is always executed whether exception is handled or not. Even though their is an error and it reaches to catch block, it will go to finally block to execute the piece of code.
finally block is a block that is used to execute important code such
as closing connection, stream etc.
So, Inside try{} block you placed try and finally, but you asked about the catch of outside try ,thus its not going inside the first try block.That finally wont work.
P.S. : If you put finally something like this:
try{
try{...}
finally{...}
}catch(Exception e){...}
finally{... }
//in case of exception also , the outside finally is going to work.
P.S.: Though you got your answer , but the concept is for reference of other naive programmers
An uglier variant (sometimes generated by the IDE) one sees also:
// *** UGLY
PrintWriter out = null;
try {
out = new PrintWriter(filename);
//output
} catch (IOException e) {
//handle exception
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e2) {
// IGNORE
}
}
}
That explains the code a bit: as close may throw an IOException too, the code becomes cumbersome. Your code still needs nested exceptions.
With try-with-resources this can & should be written as:
try (PrintWriter out = new PrintWriter(filename)) {
//output
} catch (IOException e) {
//handle exception
} // Automatically closes.
And no longer nested exceptions.
The biggest advantage is that you need not catch any exception, and just add a throws IOException in the method signature.

Try With Resources vs Try-Catch [duplicate]

This question already has answers here:
What's the purpose of try-with-resources statements?
(7 answers)
Closed 2 years ago.
I have been looking at code and I have seen try with resources. I have used the standard try-catch statement before and it looks like they do the same thing. So my question is Try With Resources vs Try-Catch what are the differences between those, and which is better.
Here is a try with resources :
objects jar = new objects("brand");
objects can= new objects("brand");
try (FileOutputStream outStream = new FileOutputStream("people.bin")){
ObjectOutputStream stream = new ObjectOutputStream(outStream);
stream.writeObject(jar);
stream.writeObject(can);
stream.close();
} catch(FileNotFoundException e) {
System.out.println("sorry it didn't work out");
} catch(IOException f) {
System.out.println("sorry it didn't work out");
}
The main point of try-with-resources is to make sure resources are closed reliably without possibly losing information.
When you don't use try-with-resources there's a potential pitfall called exception-masking. When code in a try block throws an exception, and the close method in the finally also throws an exception, the exception thrown by the try block gets lost and the exception thrown in the finally gets propagated. This is usually unfortunate, since the exception thrown on close is something unhelpful while the informative one is the one thrown from within the try block. (So instead of seeing the SQLException that tells you which referential integrity constraint was violated, you're shown something like BrokenPipeException where closing the resource failed.)
This exception-masking is an annoying problem that try-with-resources prevents from happening.
As part of making sure exception-masking wouldn't lose important exception information, when try-with-resources was developed they had to decide what to do with the exceptions thrown from the close method.
With try-with-resources, if the try block throws an exception and the close method also throws an exception, then the exception from the close block gets tacked on to the original exception:
... there are situations where two independent exceptions can be thrown in sibling code blocks, in particular in the try block of a try-with-resources statement and the compiler-generated finally block which closes the resource. In these situations, only one of the thrown exceptions can be propagated. In the try-with-resources statement, when there are two such exceptions, the exception originating from the try block is propagated and the exception from the finally block is added to the list of exceptions suppressed by the exception from the try block. As an exception unwinds the stack, it can accumulate multiple suppressed exceptions.
On the other hand if your code completes normally but the resource you're using throws an exception on close, that exception (which would get suppressed if the code in the try block threw anything) gets thrown. That means that if you have some JDBC code where a ResultSet or PreparedStatement is closed by try-with-resources, an exception resulting from some infrastructure glitch when a JDBC object gets closed can be thrown and can rollback an operation that otherwise would have completed successfully.
Without try-with-resources whether the close method exception gets thrown is up to the application code. If it gets thrown in a finally block when the try block throws an exception, the exception from the finally block will mask the other exception. But the developer has the option of catching the exception thrown on close and not propagating it.
You missed something, the finally block. The try-with-resouces will make it something like,
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream("people.bin");
ObjectOutputStream stream = new ObjectOutputStream(outStream);
stream.writeObject(jar);
stream.writeObject(can);
stream.close();
} catch(FileNotFoundException e) {
System.out.println("sorry it didn't work out");
} catch(IOException f) {
System.out.println("sorry it didn't work out");
} finally {
if (outStream != null) {
try {
outStream.close();
} catch (Exception e) {
}
}
}
Which means you really wanted something like (never swallow exceptions),
try (FileOutputStream outStream = new FileOutputStream("people.bin");
ObjectOutputStream stream = new ObjectOutputStream(outStream);) {
stream.writeObject(jar);
stream.writeObject(can);
// stream.close(); // <-- closed by try-with-resources.
} catch(FileNotFoundException e) {
System.out.println("sorry it didn't work out");
e.printStackTrace();
} catch(IOException f) {
System.out.println("sorry it didn't work out");
e.printStackTrace();
}
The only difference is that try-resource is adding automatically resource.close();
as you would do in finally block
Any object (either the class or their superclass) that implements java.lang.AutoCloseable or java.io.Closeable
can only be used in try-with-resource clause.
AutoClosable interface is the parent interface and Closable interface extends the AutoClosable interface.AutoClosable interface has method close which throws Exception while Closable interface has method that throws IOException.
We can also have catch and finally block followed by try-with-resource like ordinary try, catch and finally, but catch and finally block only get executed once the resource declared inside the try-with-resource clause is closed.
Succinctly it is syntactic sugar to support the AutoClosable interface and call the close() method for you for any outcome.

I just write a wrapcommand in java but sometimes it do not print the command output. WHY

I just write a simple commandwrapper in java, this is construction function:
Process process;
Thread in;
Thread out;
public CommandWrapper(Process process) {
this.process = process;
final InputStream inputStream = process.getInputStream();
// final BufferedReader
//final BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
final byte[] buffer = new byte[1024];
out = new Thread() {
// String line;
int lineNumber = 0;
public void run() {
try {
while (true) {
int count = inputStream.read(buffer);
System.out.println(lineNumber + ":"
+ new String(buffer, 0, count - 1));
// line=r.readLine();
// System.out.println(lineNumber+":"+line);
lineNumber++;
}
} catch (Exception e) {
}
}
};
final BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
final OutputStream outputStream = process.getOutputStream();
in = new Thread() {
String line;
public void run() {
try {
//while (true) {
outputStream.write((reader.readLine() + "/n")
.getBytes());
outputStream.flush();
//}
} catch (Exception e) {
}
}
};
}
public void startIn() {
in.start();
}
This is when it invoke:
public static void main(String[] args) {
try {
CommandWrapper command = new CommandWrapper(Runtime.getRuntime()
.exec("wget www.google.com"));
//command.startIn();
command.startOut();
} catch (Exception e) {
e.printStackTrace();
}
}
It works OK when I run simple command like ls -l or other local commander, but when I want to run wget command it is print out nothing as output. I do know why.
From the code you've shown and your description of how you use it, the best guess is that an exception occurs, and you silently swallow it. This happens whenever you have an empty catch-block, like this:
catch (Exception e) {
}
You happen to have one in the run() method of your out thread.
Silently swallowing exceptions is extremely bad practice.
You should never ever ever do this! Depending on your application the appropriate solution varies, but since you're writing a console application you probably want to print the stack trace of the exception. In Java, this is done with e.printStackTrace():
catch (Exception e) {
e.printStackTrace();
}
Another option (which might not be appropriate in this specific case) is to rethrow the exception, possibly after wrapping it in another exception (for example one you've written specifically for your application):
catch (Exception e) {
throw e;
}
// or
catch (Exception e) {
throw new MyOwnException(e);
}
Doing either of these two (printing stack trace or rethrowing) will ensure that no exceptions go unnoticed.
However, no rule without exceptions ;)
There are cases when it is appropriate to have empty catch-clauses. If you know that some operation might throw an exception and you just want to proceed when it happens, an empty catch-clause is a good way to do it. However, the cases where this is appropriated are limited to (at least) the following conditions:
You must know the specific type of the exception. You never want to catch a general exception (i.e. catch (Exception e) since that might be thrown for any reason which you cannot possibly predict. If you use empty catch clauses, always catch specific exception type (such as IOException).
You must know why the exception was thrown. You should only swallow exceptions that you know the origin of. If you swallow any other exceptions, you'll end up like in this situation, where your code doesn't do what you expect and you can't understand why. Swallowed exceptions are extremely difficult to debug, since they are, well, swallowed, and thereby hidden.
You must know that you don't care about the exception. The reason to use empty catch-clauses is mainly (read: only) to handle situations where the code you're using treats something as exceptional, while you do not. By exeptional in this context we mean "something that shouldn't really happen, and if it does, something is seriously wrong."
An example of when empty catch-clauses are appropriate:
Say that you are using someone elses code that opens a file for reading, given the absolute path of the file. Most such routines throw exceptions if the file does not exist - it is the job of the client code (i.e. the code that calls the "open file routine") to ensure that the file exists before trying to open it. Exceptions will also be thrown if, for example, the user running the program does not have permissions to read the file.
Now, you might not really care why the file couldn't be opened, but if it couldn't you just want to keep going - in that case, you swallow all exceptions related to reading the file (in Java, likely an IOException of some sort). Note that you do not swallow all exceptions - only the ones related to opening the file!

Catch Exception in finally { } ? Must?

I feel puzzle ...
I write a small routine in .jsp. Finally, ResultSet, Statement and Connection are required to be closed. I also write the closing codes in finally { }, but when the page is run, it return error that I didn't catch exception ...
I read some forum. Other people didn't catch any exception in finally { }
Any Hint ?
Sounds like you have the old problem of needing to close() in a finally block but close() throws an exception itself. Try somethig like the following...
ResultSet rs;
try {
// do various stuff
rs = ...;
} finally {
try {
if (rs != null) rs.close();
} catch (SQLException e) {
// do something with exception
}
}
You must catch exceptions in the code finally block. As you must catch exceptions in the catch block. Nested try/catches are a regular thing (albeit ugly).
One important note here is that you could have the exceptions that occur in finally declared in the throws clause of the method. However that would lead to the exception in finally overriding the original exception, which is lost. And you will see, for example, a NullPointerException, rather than FileNotFoundException.
By the way, avoid having code in the JSP file. Place it in a servlet.
finally{} doesn't do any exception catching. A finally{} block exists to make sure that certain code is run, no matter whether the try{} block reached its natural end or if it's jumping temporarily to the finally{} because an exception happened and that finally{} block was along the way. But after the finally{} finishes, the exception goes about its merry business, cavorting its way up the stack and cheerfully crashing your program.
If you want to actually catch the exception and stop it from unwinding the stack further, use catch(){}. But don't use catch blindly- catching an exception you don't actually know how to recover from is much worse than crashing, because now your program isn't working correctly and you don't have an exception stack trace telling you why.
Your ResultSet, Statement, and Connection almost certainly did get closed. And then the exception continued happening and crashed your program anyway, because that had nothing to do with your ResultSet, Statement, and Connection.
What was the actual exception?
Maybe I'm getting old, but what's wrong with catching exceptions in the catch block?
It helps if you say what is in your try block. You are probably not catching appropriate exception or your code in finally throws exception.
It is OK to have finally without catch.
try {
//do some work
}
finally {
//check of state and do clean up. You would have reached here via multiple branches.
}
It more appropriate to catch specific exceptions using catch and then handle specific cleanup there. Use finally for any code that must get executed even when exception happen.
try {
//do some work
}
catch ( RecoverableException1 re1) {
//cleanup
}
catch ( RecoverableException2 re2) {
//cleanup
}
finally {
//check of state and do clean up. You would have reached here via multiple branches.
}
finally{
try{
resultSet.close();
}catch(E e){
}finally{
try{
statement.close();
}catch(E e){
}finally{
conn.close();
}
}
}

Java exception handling

How do I use exceptions and exception handling to make my program continue even if an exception occurs while processing certain files in a set of files?
I want my program to work fine for correct files while for those files which cause an exception in program, it should ignore.
Regards,
magggi
for(File f : files){
try {
process(f); // may throw various exceptions
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
You have to use the try/catch/finally blocs.
try{
//Sensitive code
} catch(ExceptionType e){
//Handle exceptions of type ExceptionType or its subclasses
} finally {
//Code ALWAYS executed
}
try will allow you to execute sensitive code which could throw an exception.
catch will handle a particular exception (or any subtype of this exception).
finally will help to execute statements even if an exception is thrown and not catched.
In your case
for(File f : getFiles()){
//You might want to open a file and read it
InputStream fis;
//You might want to write into a file
OutputStream fos;
try{
handleFile(f);
fis = new FileInputStream(f);
fos = new FileOutputStream(f);
} catch(IOException e){
//Handle exceptions due to bad IO
} finally {
//In fact you should do a try/catch for each close operation.
//It was just too verbose to be put here.
try{
//If you handle streams, don't forget to close them.
fis.close();
fos.close();
}catch(IOException e){
//Handle the fact that close didn't work well.
}
}
}
Resources :
oracle.com - Lesson: Exceptions
JLS - exceptions
I guess your new to programming as execeptions are a fairly fundermental concept, as problems can happen out of your control and you need to deal with it.
The basic premise is a try catch block.
try
{
//Your code here that causes problems
}
catch(exception ex)
{
//Your code to handle the exception
}
You 'try' your code, and if an exception is raised, you 'catch' it. And do what you need.
There is also an addition to the catch block in that you can add finally{} below it. Basically even if no exception is raised the finally code is still run. You may wonder the point in this, but its often used with streams/file handling etc to close the stream.
Read more on java exceptions here in tutorials written by Sun (now Oracle)- http://download.oracle.com/javase/tutorial/essential/exceptions/
try
{
//Your code here that causes problems
}
catch(exception ex)
{
//Your code to handle the exception
}
finally
{
//Always do this, i.e. try to read a file, catch any errors, always close the file
}
The question you may ask is how do you catch different exceptions, i.e. is it a null reference, is it divide by zero, is it no file found or file not writeable etc. For this you write several different catch blocks under the try, basically one catch for each type of exception, the use of "exception" is basically a catch all statement, and like in stack of if statements if an "exception" is the first catch block it will catch everything, so if you have several catch blocks ensure exception is the last one.
Again, this is a useful but large topic so you need to read up about it.
Since you are doing multiple files, you need to basically do a loop and within the loop is contained the try/catch block.
so even if one file fails, you catch it, but carry on running, the code will then loop around onto the next file unhindered.
just catch the excpetion it may throw and do nothing with it; eat it as people say :)
But at least log it!
Very concise example:
try {
your code...
} catch (Exception e) {
log here
}
Typically, I would have done this.
ArrayList<Entry> allEntries = getAllEntries();
for(Entry eachEntry:allEntries){
try{
//do all your processing for eachEntry
} catch(Exception e{
ignoredEntries.add(eachEntry);
//if concerned, you can store even the specific problem.
} finally{
//In case of resource release
}
}
if(ignoredEntries.size() > 0){
//Handle this scenario, may be display the error to the user
}
FileSystemException may be the specific exception you are looking for.
Although, a better idea for beginners is to catch an exception and print it using
System.out.println(e);
where e is the caught exception.
public class Main
{
public static void main(String args[])
{
int a=10;
try
{
System.out.println(a/0); //Here it is not possible in maths so it goes to catch block
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception");
}
}
}
output:Arithmetic Exception
Exception in java are runtime error which can be handled by the program, the process is called as exception handling. Parent class of exception is Throwable.
Exception : Exception are those runtime error which can be handled by program.
Error : Those runtime error which can’nt handled by the program.
Tools used to handle Exception:
Try
Catch
Finally
Throw
Throws
more

Categories