rethrowing exception in finally block [duplicate] - java

This question already has answers here:
Exception thrown in catch and finally clause
(12 answers)
Closed 7 years ago.
I have written a function as below, In try block I am throwing IOException which is handled by next catch block and its again throwing FileNotFoundException, In the finally block I again throw a NULLPointerException. so my question is FileNotFOundException exception is unhandled exception?
why the caller function only get NULLPointerException only,Although FileNotFounException is unhandled(what I am assuming)?
static void fun(){
try{
throw new IOException();
}
catch(IOException e){
throw new FileNotFoundException();
}
finally{
throw new NullPointerException();
}
}

You aren't using the finally statement correctly.
According to the Java docs:
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
So, yes, you do have an unhandled exception. If you are trying to handle multiple errors, I'd throw exceptions, rather than using a try/catch like this:
static void fun() throws FileNotFoundException, NullPointerException{
//your code here
}
Then when you call the method, you can surround that in a try/catch:
try{
YourClass.fun();
}catch(Exception e){
//handle the error.
}finally{
//clean up code, this is optional
}

You can only throw one exception at a time unless you're wrapping old ones inside of new ones. Finally is last so it wins.
Since you're obviously not posting working code but code meant to explore this issue and demonstrate behavior I won't bother correcting you. I will point you to some code that deals with a very real problem that follows from this issue.
The problem comes up when you try to close something in finally and the close method itself throws an exception. You end up needing a second try.

Yes, FileNotFoundException is unhandled. To handle it, surround fun() with another trycatch block.
try{
fun();
catch(FileNotFoundException ex){
}
catch(NullPointerException ex){
}

Related

How to fix unreported IO Exception. Trying to read a specific line from a .txt file [duplicate]

This question already has an answer here:
What does "error: unreported exception <XXX>; must be caught or declared to be thrown" mean and how do I fix it?
(1 answer)
Closed 8 months ago.
While learning Java I stumble upon this error quite often. It goes like this:
Unreported exception java.io.FileNotFound exception; must be caught or declared to be thrown.
java.io.FileNotFound is just an example, I've seen many different ones. In this particular case, code causing the error is:
OutputStream out = new BufferedOutputStream(new FileOutputStream(new File("myfile.pdf")));
Error always disappears and code compiles & runs successfully once I put the statement inside try/catch block. Sometimes it's good enough for me, but sometimes not.
First, examples I'm learning from do not always use try/catch and should work nevertheless, apparently.
Whats more important, sometimes when I put whole code inside try/catch it cannot work at all. E.g. in this particular case I need to out.close(); in finally{ } block; but if the statement above itself is inside the try{ }, finally{} doesnt "see" out and thus cannot close it.
My first idea was to import java.io.FileNotFound; or another relevant exception, but it didnt help.
What you're referring to are checked exceptions, meaning they must be declared or handled. The standard construct for dealing with files in Java looks something like this:
InputStream in = null;
try {
in = new InputStream(...);
// do stuff
} catch (IOException e) {
// do whatever
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
}
}
}
Is it ugly? Sure. Is it verbose? Sure. Java 7 will make it a little better with ARM blocks but until then you're stuck with the above.
You can also let the caller handle exceptions:
public void doStuff() throws IOException {
InputStream in = new InputStream(...);
// do stuff
in.close();
}
although even then the close() should probably be wrapped in a finally block.
But the above function declaration says that this method can throw an IOException. Since that's a checked exception the caller of this function will need to catch it (or declare it so its caller can deal with it and so on).
Java's checked exceptions make programmers address issues like this. (That's a good thing in my opinion, even if sweeping bugs under the carpet is easier.)
You should take some appropriate action if a failure occurs. Typically the handling should be at a different layer from where the exception was thrown.
Resource should be handled correctly, which takes the form:
acquire();
try {
use();
} finally {
release();
}
Never put the acquire() within the try block. Never put anything between the acquire() and try (other than a simple assign). Do not attempt to release multiple resources in a single finally block.
So, we have two different issues. Unfortunately the Java syntax mixes up the two. The correct way to write such code is:
try {
final FileOutputStream rawOut = new FileOutputStream(file);
try {
OutputStream out = new BufferedOutputStream(rawOut);
...
out.flush();
} finally {
rawOut.close();
}
} catch (FileNotFoundException exc) {
...do something not being able to create file...
} catch (IOException exc) {
...handle create file but borked - oops...
}

Java know in finally that exception thrown without any variable [duplicate]

In Java, is there an elegant way to detect if an exception occurred prior to running the finally block? When dealing with "close()" statements, it's common to need exception handling within the finally block. Ideally, we'd want to maintain both exceptions and propagate them up (as both of them may contain useful information). The only way I can think of to do this is to have a variable outside the try-catch-finally scope to save a reference to a thrown exception. Then propagate the "saved" exception up with any that occur in the finally block.
Is there a more elegant way of doing this? Perhaps an API call that will reveal this?
Here's some rough code of what I'm talking about:
Throwable t = null;
try {
stream.write(buffer);
} catch(IOException e) {
t = e; //Need to save this exception for finally
throw e;
} finally {
try {
stream.close(); //may throw exception
} catch(IOException e) {
//Is there something better than saving the exception from the exception block?
if(t!=null) {
//propagate the read exception as the "cause"--not great, but you see what I mean.
throw new IOException("Could not close in finally block: " + e.getMessage(),t);
} else {
throw e; //just pass it up
}
}//end close
}
Obviously, there are a number of other similar kludges that might involve saving the exception as an member variable, returning it from a method, etc... but I'm looking for something a bit more elegant.
Maybe something like Thread.getPendingException() or something similar? For that matter, is there an elegant solution in other languages?
This question actually spawned from comments in another question that raised an interesting question.
Your idea about setting a variable outside the scope of the try/catch/finally is correct.
There cannot be more than one exception propagating at once.
Instead of using a Boolean flag, I would store a reference to the Exception object.
That way, you not only have a way to check whether an exception occurred (the object will be null if no exception occurred), but you'll also have access to the exception object itself in your finally block if an exception did occur. You just have to remember to set the error object in all your catch blocks (iff rethrowing the error).
I think this is a missing C# language feature that should be added. The finally block should support a reference to the base Exception class similar to how the catch block supports it, so that a reference to the propagating exception is available to the finally block. This would be an easy task for the compiler, saving us the work of manually creating a local Exception variable and remembering to manually set its value before re-throwing an error, as well as preventing us from making the mistake of setting the Exception variable when not re-throwing an error (remember, it's only the uncaught exceptions we want to make visible to the finally block).
finally (Exception main_exception)
{
try
{
//cleanup that may throw an error (absolutely unpredictably)
}
catch (Exception err)
{
//Instead of throwing another error,
//just add data to main exception mentioning that an error occurred in the finally block!
main_exception.Data.Add( "finally_error", err );
//main exception propagates from finally block normally, with additional data
}
}
As demonstrated above... the reason that I'd like the exception available in the finally block, is that if my finally block did catch an exception of its own, then instead of overwriting the main exception by throwing a new error (bad) or just ignoring the error (also bad), it could add the error as additional data to the original error.
You could always set a boolean flag in your catch(es). I don't know of any "slick" way to do it, but then I'm more of a .Net guy.
Use logging...
try {
stream.write(buffer);
} catch(IOException ex) {
if (LOG.isErrorEnabled()) { // You can use log level whatever you want
LOG.error("Something wrong: " + ex.getMessage(), ex);
}
throw ex;
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException ex) {
if (LOG.isWarnEnabled()) {
LOG.warn("Could not close in finally block", ex);
}
}
}
}
In vb.net, it's possible to use a "Catch...When" statement to grab an exception to a local variable without having to actually catch it. This has a number of advantages. Among them:
If nothing is going to 'ultimately' catch the exception, an unhandled exception trap will be fired from the spot of the original exception. Much nicer than having the debugger trap at the last rethrow, especially since information that might be needed for debugging won't yet have gone out of scope or been swept up by 'finally' statements.
Although a rethrow won't clear the stack trace the way "Throw Ex" would, it will still often jinx the stack trace. If the exception isn't caught, the stack trace will be clean.
Because this feature is unsupported in vb, it may be helpful to write a vb wrapper to implement the code in C (e.g. given a MethodInvoker and an Action(Of Exception), perform the MethodInvoker within a "Try" and the Action in a "Finally".
One interesting quirk: it's possible for the Catch-When to see an exception which will end up getting overwritten by a Finally-clause exception. In some cases, this may be a good thing; in other cases it may be confusing. In any event, it's something to be aware of.

How to go to catch block without throwing exception

I have a java class which is throwing IOException.I have some code in Catch block which i need to debug. I don't know in which case my java class is throwing exception. So I need to go to catch block explicitly without throwing. Can it be possible.
Please help me out.
Code in a catch block is not executed if no matching exception is thrown in the try block.
The only way to execute it is to cause the IOException to be thrown.
You can just put an explicit throw new IOException(); as the last line in the try block.
Alternatively, you might be able to pull the contents of the catch block into a separate method, which you can then invoke explicitly.
Control wont goto catch block if exception is not thrown. Put the code in finally block which you want to execute irrespective of whether exception thrown or not.
Sample:
try {
} catch() {
} finally {
//Put code here
}
but if the exception is thrown you will be directed towards finally block or you can post sample code so one might help you

Catching versus Throwing Exceptions in Java [duplicate]

This question already has answers here:
When to catch the Exception vs When to throw the Exceptions?
(8 answers)
Closed 3 years ago.
So I have two general questions about java in general. The first is when would one use a try/catch in the body of the method versus using throws exception in declaring the method? Here is a little demonstration of what I mean. This:
public void whileChatting() throws IOException{}
versus
public void closeConnection() {
try {
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
And then my second question is when does one know what type of exception to either catch or throw? By that I mean exceptions such as IOException or EOFException and so on...
If there's a good link someone could send me teaching all this (being that it's probably more complicated than I think) I would be just as grateful as if you answered it.
Thanks.
Throwing Exceptions
In your first example,
public void whileChatting() throws IOException{}
means that it will just throw the exception to whatever is calling the function. It can then be caught while calling that method with a try-catch block. such as
try{
whileChatting();
}
catch(IOException e){
e.printStackTrace();
}
Throwing a method basically propagates it up the chain, and so any method that calls this method will need to also include throws IOException, or the exception will need to be dealt with in the higher level method (by means of a try-catch block usually).
Catching Exceptions
Catching an exception is a way to gracefully deal with exceptions. The common thing to do is e.printStackTrace(); which prints details of the error to the console, however it's not always necessary. Sometimes you may want to do a System.exit(0) or even a System.out.println("Error in method whileCalling()")
With a catch block you can catch any type of exception! you can also do a try-catch-finally block which will run the code in the try block, catch any exceptions, and whether or not any exceptions are caught it will enter the finally block and run that code.
To know what Exception you might need to catch, you can look at the Javadocs for the class that may throw the exception. There you will find a list of every possible thing that the class can throw. You can also just catch Exception which will catch any Exception imaginable! (Well, granted it extends Exception)
And finally you can link catch blocks together like so.
try{
whileCalling();
}
catch(IOException e){
//handle this situation
}
catch(FileNotFoundException e){
//handle this situation
}
catch(Exception e){
//handle this situation
}
This will work like and else-if block and not catch duplicates.
So to answer your questions basically:
1: To throw an Exception means to have somebody else deal with it, whether this be another class, another method, or just to hoping it doesn't happen or else your program will crash(pretty bad practice).
2: To use a try catch block is to actually deal with the Exception however you see fit! printing out the stacktrace for debugging or giving the user a new prompt to re-input something maybe. (For instance a prompt that the user needs to enter a file location and then it throws a FileNotFoundException)
Hope that helps!
Two good rules of thumb:
You should only catch exceptions that you can actually handle
Throw Early/Catch Late
There's no hard and fast answer.
In general, you'll probably use "throws" much more often than you'll have a custom "try/catch". Simply because you'll have relatively few "decision" modules that "know how to recover", but you'll have correspondingly "many" modules that could throw exceptions.
You use try/catch when you want to treat its reason, otherwise you should propagate it so it can be treated at the right time.
A good start would be javadoc and tutorialspoint for exceptions
Basically is something like this:
throws - the function that throws and exception tells it's parent function that somenthing it's wrong. For instance you have a createFunction() throws SQLException where you are trying to insert 100 item in a database but the creation of number 98 fails. The createFunction() is used in your main() who receives this SQLException;
try/catch - the main() knows that createFunction() is suppose to throw an SQLException if something goes wrong so when it implements it puts it in a try/catch block, this way if an SQLException is actually thrown you can execute a fall-back plan in the catch block such as a database rollback.
Actual code of what I just said:
createFunction(Connection connection) throws SQLException {
//insert items in the database
}
main(){
try{
createFunction(connection);
}
catch (SQLException e){
connection.rollback();
}
}

try ,catch, finally execution [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
throws Exception in finally blocks
The catch block is only executed if an exception is thrown in the try block.
The finally block is executed always after the try(-catch) block, if an exception is thrown or not.
My question is IF I got Exception in finally block than how to handle it ?????
This is a well-known problem/gotcha in the Java language specification, in the sense that if an exception is thrown within the finally clause (without handling it in a nested try-catch) , the original exception gets lost. You will need to nest a new try-catch to catch the new exception, and process it there.
You have to handle Exception in finally block
like
finally{
try
{
///
}
catch(Exception e)
{
///
}
}

Categories