If I have the method:
public static boolean getA() throws Exception{
try{
throw new Exception();
}finally
{
}
}
There is no return statement required. Moreover, if we try to add a return statement at the end, it produces the "unreachable statement" error.
Why is this so? Is it certain the the program will not come out of the block, and that the exception will be thrown?
Furthermore, if we add a catch block instead of the finally block, then it requires the return statement to be present there.
Because you have specified an throw statement and there is nothing else in the method definition. That is why. I guess it was that simple.
The return statement will be unreachable, because it is going to throw the exception irrespective of everything.
The catch will require the return statement, because you are handling the exception explicitly now it wants you to return as you have declared in the method definition.
I hope you are aware, you can keep both catch and finally blocks. Because they serve different purpose of their own.
Java Exceptions.
Yes it is certain that the program will throw an exception, this is the first line of what you're doing in your try block.
Even if it wasn't the first statement in your try block, you don't have a catch block so any other theoretically previously thrown exception would not be caught.
It might be because when you throw an exeception, execution stops, hence why finally will never run. When you catch the exception, execution will proceed, and you will have to return.
Related
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.
'Hi, everyone! I have a question about exception handling in Java. What is launched firstly if there is sequential "throw" declarations and why? Below is an example of a method like that:
public void myMethod(boolean ok) {
if (ok) {
// do something...
} else {
throw new myRuntimeException();
throw new RuntimeException ();
}
}
Thanks in advance!
Most compiler would flag the second "throw" as error : "Unreachable code" - as it will never get executed.
It would be like writing code after a return (except a finally block) - it is never going to get executed - hence illegal.
Once you throw, the flow of execution is interrupted and the following happens:
if you are inside a try block, it goes to to the corresponding catch
if not, the Throwable (Exception in your case) is passed up the call chain, leaving myMethod() and going to the method that called it
this process is repeated until you either reach a try block or the top of the call stack, in which case your program will terminate.
Thus, only your first exception is thrown, the throw new RuntimeException (); statement is never reached.
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
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();
}
}
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){
}