Fail fast finally clause in Java - java

Is there a way to detect, from within the finally clause, that an exception is in the process of being thrown?
See the example below:
try {
// code that may or may not throw an exception
} finally {
SomeCleanupFunctionThatThrows();
// if currently executing an exception, exit the program,
// otherwise just let the exception thrown by the function
// above propagate
}
or is ignoring one of the exceptions the only thing you can do?
In C++ it doesn't even let you ignore one of the exceptions and just calls terminate(). Most other languages use the same rules as java.

Set a flag variable, then check for it in the finally clause, like so:
boolean exceptionThrown = true;
try {
mightThrowAnException();
exceptionThrown = false;
} finally {
if (exceptionThrown) {
// Whatever you want to do
}
}

If you find yourself doing this, then you might have a problem with your design. The idea of a "finally" block is that you want something done regardless of how the method exits. Seems to me like you don't need a finally block at all, and should just use the try-catch blocks:
try {
doSomethingDangerous(); // can throw exception
onSuccess();
} catch (Exception ex) {
onFailure();
}

If a function throws and you want to catch the exception, you'll have to wrap the function in a try block, it's the safest way. So in your example:
try {
// ...
} finally {
try {
SomeCleanupFunctionThatThrows();
} catch(Throwable t) { //or catch whatever you want here
// exception handling code, or just ignore it
}
}

Do you mean you want the finally block to act differently depending on whether the try block completed successfully?
If so, you could always do something like:
boolean exceptionThrown = false;
try {
// ...
} catch(Throwable t) {
exceptionThrown = true;
// ...
} finally {
try {
SomeCleanupFunctionThatThrows();
} catch(Throwable t) {
if(exceptionThrown) ...
}
}
That's getting pretty convoluted, though... you might want to think of a way to restructure your code to make doing this unnecessary.

No I do not believe so. The catch block will run to completion before the finally block.
try {
// code that may or may not throw an exception
} catch {
// catch block must exist.
finally {
SomeCleanupFunctionThatThrows();
// this portion is ran after catch block finishes
}
Otherwise you can add a synchronize() object that the exception code will use, that you can check in the finally block, which would help you identify if in a seperate thread you are running an exception.

Related

In Java catch block, how do you know which method/line throws the exception?

In try block, I want to execute two functions. If the first one failed then don't execute the second. I also want to print out which function failed.
See following code.
try {
a = func1();
b = func2(); //won't execute if a failed
}
catch (Exception e) {
//TODO: print a or b failed?
}
Does the language support this scenario naturally?
If not, is the following a good practice? (I cannot think of anything wrong about it. But it concerns me as I don't remember seeing any one using return in catch.)
try {
a = func1();
}
catch {
//print: a failed
return; //if a failed then skip the execution of b
}
try {
b = func2();
}
catch {
//print: b failed
}
EDIT:
Summary of comments:
throw different exception from two methods.
In this case the methods are written by others and I have no control.
e.printStackTrace() will print line number and function
I want to do more than just printing. More like, if a failed, execute the following code.
What you want is String methodName = e.getStackTrace()[0].getMethodName());
But this is hardly a good practice. The standard way is to log the exception using appropriate method in your logging framework or (if writing a console app, which is rarely the case with Java) to print it to the error or standard output or optionally to other PrintStream, for example using printStackTrace(printStream).
But in most cases you want to propagate exception to the upper layers and handle (or decide to not handle it) by the appropriate high level code. Catching exceptions like this leads to nasty bugs. Returning from catch black is also a very bad idea in 99% of cases because exception signalizes abnormal termination of the method while returning a value does not.
As dev-null wrote e.getStackTrace() can help. But note that the exception may not be thrown by func1 or func2 themselves but by some other method they call. So you need to go through all elements of the array until you hit func1 or func2.
Calling them in separate try blocks is definitely practiced but it can get cumbersome.
Logging the stack trace if an exception is thrown will inform you which line threw the exception. If the first line in the try/catch throws the exception, the next line will not be executed.
This will work:
String failedFunc = "func1";
try {
a = func1();
failedFunc = "func2";
b = func2(); //won't execute if func1() failed
} catch (Exception e) {
System.out.println("Func '" + failedFunc + "' failed: " + e);
}
Or course, if all you're doing is printing the error, then printing the stack trace will show you exactly where it failed. The above code is however useful if you need the value of failedFunc without a full stack trace.
As I said in the comments, you can use e.printStackTrace() to determine the cause of the Exception. Since you expressed a desire for different behaviors then you have a few options. You could write two local functions to decorate your func1 and func2 calls with custom Exceptions. Something like,
class Func1Exception extends Exception {
public Func1Exception(Exception e) {
super(e);
}
}
class Func2Exception extends Exception {
public Func2Exception(Exception e) {
super(e);
}
}
Then you can write the local functions like
private static Object func1Decorator() throws Func1Exception {
try {
return func1();
} catch (Exception e) {
throw new Func1Exception(e);
}
}
private static Object func2Decorator() throws Func2Exception {
try {
return func2();
} catch (Exception e) {
throw new Func2Exception(e);
}
}
Then you can handle them however you wish,
try {
a = func1Decorator();
b = func2Decorator(); // this still won't execute if a failed
} catch (Func1Exception e) {
// a failed.
} catch (Func2Exception e) {
// b failed.
}
If you want func2 to run even when a fails you could use a finally block,
try {
a = func1Decorator();
} catch (Func1Exception e) {
// a failed.
} finally {
try {
b = func2Decorator(); // this will execute if a fails
} catch (Func2Exception e) {
// b failed.
}
}

Using return in try block (Java) [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have a try block where database queries are attempted to be run and a finally block where database resources are released. If a value does not exist in the database I return null.
Is it a good idea to return in a try block?
Some example code:
try {
if (!jedis.exists(name)) {
return null; // Is this a good idea?
}
// Do database related stuff...
} catch (JedisConnectionException e) {
// Fix any problems that happen
} finally {
// Return all objects to pools and clean up
}
Is it a good idea to return in a try block?
Absolutely: if the preparation of an object to be returned fits entirely within the scope of the try block, there is no reason to extend its visibility beyond its natural boundaries.
As an illustration, this
try {
ReturnType ret = ...
// Compute ret
return ret;
} catch {
...
// need to either throw or return something
} finally {
...
}
is better than this
ReturnType ret = ...
try {
// Compute ret
} catch {
...
} finally {
...
}
return ret;
In general there is nothing wrong with returning from a try-block. However it is good practice to keep blocks short, so having irrelevant code within a try block is not great.
Maybe the following is an improvement in your case:
// assuming a String result type for sake of demonstration
String result = null;
if (jedis.exists(name)) {
try {
result = jedis.getResult(name);
} catch (JedisConnectionException e) {
LOG.error("Could not get result", e);
} finally {
jedis.close();
}
}
return result;
You probably cannot 'fix' the JedisConnectionException so I would either log (as shown above) or rethrow:
throw new MyAppException("Could not get result", e);
Don't log AND rethrow, it will give you and others headaches.
As mentioned you can also use try-with-resources in Java SE 7 if JedisConnection is a Closable:
try (JedisConnection jedis = Pool.getJedisConnection()) {
result = jedis.getResult(name);
} catch (JedisConnectionException e) {
LOG.error("Could not get result", e);
}
This will automatically close the JedisConnection after processing is done.
Consider this example. finally block will be executed even if you return in the try block. Its better to return in the finally block for better readability of code . You can trace from where your value is being returned, else you might end up with some problems figuring that out.
public static void main(String[] args) {
System.out.println(someMethod());
}
private static boolean someMethod() {
try {
System.out.println("in try");
return true;
} catch (Exception e) {
} finally {
System.out.println("in finally");
return false;
}
}
O/P :
in try
in finally
false -- > not true, but false
Even if you use return statement, the finally block would be executed.
The finally block would not be executed only when you call System.exit(0);
So, you can use your clean up code in finally block.
Using return however depends on other stuff like your solution design.
As long as finally really has to run even if !jedis.exists(name) evaluates to true, it's not only a good idea, it's practically a must. So for example, if you have a line like jedis.connect() (not real code, just an example), then the if should be inside the try, and finally should call jedis.disconnect. But if the code in your finally is fully dependent on what you would do after the check, then the if makes more sense before the try.
That depends, in your case it doesn´t matter, but as a general rule, consider this example:
String returnString="this will be returned";
try
{
// ... something that could throw SomeException
return returnString;
}
catch(SomeException ex)
{
// Exception handling
}
finally
{
returnString="this will not be returned";
}
This might be somehow confusing, since the string returned is "this will be returned", no matter what finally was trying to do.
It is OK to reaturn a value from the try block.
Consider this case also in your implementation.
private static int testFinally() {
try {
return 100;
} finally {
return 101;
}
}
here the values are returned from try block and finally block. First it will execute the try block but before return it should execute the finally block. So this method will return 101, from the finally block instead of 100.
So returning from the finally block might produce unexpected results for the casual reader.
In my view
It is better to return values inside the Try block
Return the Default values/ appropriate values inside the Catch blocks in case of exceptions.
Only do the cleanups inside the finally block.

Resume code in try block after exception is caught

I am fairly new to using try/catch blocks, so I don't know how exactly to perform this command.
If I catch an error, I would like to wait a period of time(10 seconds or so) then try to run the same line of code to attempt to continue in my try block. My program is written in Java. I have looked at both these pages: Page1, Page2, but neither of them are in Java. I have also looked at this, but they are not solving in the using the catch block. Is this possible to do, and how would I implement this in my catch block instead of just printing the error?
99% of time, you want to re-run a code-block after a try-catch and not the line with exception.
If you need to run from that line, than that is an indication for you to take your code in another method that encapsulates only that code (maybe move the try-catch there too).
What i would advice is something like this:
void method(){
try{
codeline1;
codeline2;
codeline3;
codeline4;
}
catch(Exception ex)
{
restorClassStateBeforeCodeLine1();
method();
}
}
By that snipped i propose to have your entire try-catch in a separate method.
Waiting random intervals is bad practice also. You never know if 10 seconds is right every time or at all.
Another way that I advise against would be:
label: {
try {
...
if (condition)
break label;
...
} catch (Exception e) {
...
}
}
It uses java labels to retry that part. I never tried but the break could be moved in the catch and the label in the try.
I don't think it is possible to return to a certain line in your try-block from inside a catch-block. Because when the throwis executed, the runtime system is going to pop frames from the call stack, looking for an exception handler to match the thrown exception and once the frame is popped from the stack, it's gone. More info about this can be found here
What you can do is call the method that caused the throw from within the catch-block. But that means it is going to execute your method from the beginning, so maybe you want to try to rearrange your code so that this does not cause any other problems. EDIT: The other answer demonstrates exactly what I mean.
This simple program loops through array values, testing each until it finds a value that doesn't generate an exception
public static void main(String[] args) {
int[] array=new int[]{0,0,0,0,5};
for(int i=0; i<array.length;i++) {
try {
System.out.println(10/array[i]);
break;
} catch(Exception e) {
try { Thread.sleep(1000); } catch(Exception ignore){}
}
}
}
while(true){
try{
//actions where some exception can be thrown
break;//executed when no exceptions appeared only
}
catch(YourException e){
Thread.sleep(10_000);
}
}
This cycle will be repeated while you instructions haven't executed. When code in try-block executed succesfully break helps you leave this cycle
Since you are saying that it is only 2 lines of code that you experience the intermittent error with, try something similar to this.
public static void main(String... args)
{
try
{
//Some Logic
//Error throwing logic in method
while(!doLogic())
{
Thread.sleep(1000);//Sleep here or in doLogic catch
}
//Continuing other logic!
}
catch(Exception e)
{
e.printStackTrace();
}
}
static Integer i = null;
public static boolean doLogic()
{
try
{
//Lines that throw error
System.out.println(i.toString());//NPE First run
}
catch (Exception e)
{
i = 1;
return false;
}
return true;
}

Difference between finally and write after catch

What is the difference between "finally" and write after "catch"?
For example:
public boolean example() {
try {
// Code
} catch (RuntimeException e) {
// Code
} finally {
return true;
}
}
public boolean example() {
try {
// Code
} catch (RuntimeException e) {
// Code
}
return true;
}
First of all, the only idiom that can even be considered a candidate is this:
try {
// stuff
} catch (Throwable t) {
// handle
}
// finally stuff
Note the caught type. Only if you catch any possible exception, including such dark monsters as ThreadDeath and VirtualMachineError can you hope to unconditionally reach the code below the try-catch.
But, that's only where it begins. What if the handling code itself throws an exception? So you need at least
try {
// main stuff
} catch (Throwable t) {
try {
// handle
} catch (Throwable t) {
// no code allowed here! Otherwise we descend into
// infinite recursion
}
}
// finally stuff
Now you may be beginning to realize the benefits of finally, but that's not all. Consider a quite typical scenario:
try {
// main stuff, may throw an exception. I want the exception to
// break what I'm doing here and propagate to the caller.
return true;
} finally {
// clean up, even if about to propagate the exception
}
How do you rewrite this? Without code duplication, impossible.
In the code you have provided there is no difference. But finally is used to run some piece of code after the try block no matter whether there is an exception or not.
Interesting point to make here is, we should avoid to return from the finally block because it can create confusion in scenarion when we return something from try block as well. Consider this piece of code:
try {
return true;
}
finally {
return false;
}
Now this code will return false no matter what happens in try. In many ways this behaviour is exactly consistent with the colloquial understanding of what finally means - "no matter what happens beforehand in the try block, always run this code." Hence if you return true from a finally block, the overall effect must always to be to return true, no?
In general, this is seldom a good idiom, and you should use finally
blocks liberally for cleaning up/closing resources but rarely if ever
return a value from them.
No difference in Your case. but
The runtime system always executes the statements within the finally block regardless of what happens within the try block.
So it's the perfect place to perform cleanup.
Note that if you're using JDK 7+, then most uses of the finally block can be eliminated, simply by using a try-with-resources statement.
We use try block, catch block and finally block to handle Exception in our program. A program may be have check or unchecked Exception. so this block are are used to handle those Exception. In the try block we mention or write those code which may be cause of an Exception and if we want that our code will be run if Exception occurred Then we write those code in the catch block. finally is a very special block which give us a special feature that if our catch block doesn't run then before the program goes to terminate that finally block code definitely execute. mostly this is use to save our data during unwanted program termination. if we use try block then there must be a catch block after the try block but finally is an optional not compulsory.
First thing to understand in this question is "why we use try{ } catch{ } block" Ok.
The answer is,when there is a possibility of our code of throwing an exception.
These kind of code we put in try{... } block &
catch {...} block contain the code to catch the exception generated by code in try{ } block.
Finally{...} block contain the code executed immediately after try{} catch{} block when try{ } block throws an exception.
e.g When you visit some website,but do to some server side problem it couldn't and page display some kind of message like "404 error or server is updating",these kind of code is written in finally block.
this simple catch only is for catch eXception and process it, but finally, execute if Exception or not , for example for close connections.
Finally block is useful to cleanup your code like closing open streams.
E.g:
File f = new File("\file.txt");
FileStream fs;
try{
fs = new FileStream(f);
} catch (IOException ioe){
ioe.printStackTrace();
} finally {
if (fs != null) {
fs.close() // close the stream
}
}
As your code only returning true/false , so it won't impact much . But think for any other code/logic where some mandatory/cleanup code is written to execute.
Also, it will difficult to catch all the exceptions via our code or in other words, we should catch specific exceptions which we can handle. At that point , finally will be real savior, as it will always execute(other than System.exit() or in some recursion case).
Also, for bringing the consistency in our code, one should always use finally block to perform any clean up code.
You may refer the below posts too for more clarification:
Using finally block vs writing code after the try/catch block
Try-catch-finally-return clarification
First Case:
If exception occurred in try block then catch block would be executed, and while serving the same catch block if there is again exception occurred then finally block would execute.
Second Case:
If exception occurred in try block then catch block would be executed, and if there is further exception in the same catch block then "return true;" would execute.
finally() is used whenever we want that some line of code should be executed even if exception occurs
But if u write line of code after catch it will not execute if exception occurs..

How to make a try-catch block that keeps on calling a method on an object until there are no more exceptions to catch

Basically iterating through a list and,
- Invoke method on first object
- Catch the first exception (if any); if there are no more exceptions to catch, return normally. Otherwise, keep on invoking method until all exceptions are caught.
- Move on to next object.
I can iterate through each object, invoke the method, and catch one exception but I do not know how to continuously invoke the method on it and keep on catching exceptions.
This is similar to the other answers, but without the flag, which seems like clutter to me. I don't really understand the question though, so I'm just throwing it out there in case it is useful.
for (Item item : items) {
while (true) {
try {
item.doSomething();
break;
} catch (MyException ex) {
log.warn("Something failed.", ex);
}
}
}
This approach hinges on the operation of the unlabeled break statement, which completes abruptly and then exits the enclosing while statement normally.
Based on subsequent comments, I think there is some confusion about what it means when there are multiple exceptions declared to be thrown by a method.
Each invocation of a method can be terminated by just one exception being thrown. You can't somehow resume invocation where it left off, and handle subsequent exceptions.
So, if a method throws multiple exceptions, catch a common ancestor, and move on. For example, if a method throws java.io.EOFException or java.nio.channels.ClosedChannelException, you could simply catch java.io.IOException since it is a common ancestor. (You could also catch java.lang.Exception or java.lang.Throwable for the same reason.) Invoking the method again under the same conditions won't get you any further.
If you want to attempt to invoke the method on each object, even if some fail, use this:
for (Item item : items) {
try {
item.doSomething();
} catch (Exception ex) { /* This could be any common ancestor. */
log.warn("Something failed.", ex);
}
}
If you're talking about dealing with a single method call that will throw more than one exception, it can't be done -- no matter how many times you call the method, it will keep on throwing the first exception. You can't go back into the method and keep running from there; after throwing one exception, it's all over.
But if you're talking about a method that sometimes throws exceptions and sometimes doesn't, try something like this:
boolean thrown = false;
do {
try {
thrown = false;
method();
}
catch (Exception e) {
thrown = true;
// Handle as you like
}
} (while thrown);
This is what I understand.
You have an object's method which may throw a number of exceptions.
What you want to do is to catch them all and continue with the next object in the list.
Is that correct?
So, that would be:
for( YourObject o : yourList ) {
try {
o.thatMethod();//invoke that risky method
} catch( SomeExceptionClass sec ) {
// Do something with that exception
} catch( SomeOtherExceptionClass soec ) {
// Do something with that exception
} catch( YetAnotherxceptionClass yaec ) {
// Do something with that exception
} catch( OtherUnRelatedException oue ) {
// Do something with that exception
}
}
When you do this, if the invocation of thatMethod() throws an exception and that exception is listed in the catch section, the execution flow will jump to that exception and after it will continue to the normal flow ( which is the for loop and will continue with the next object )
I hope this is what to need. For more information read: The catch block in the Java Tutorial section Essential classes
I'm assuming that you are trying to performs some kind of validation to the items in a list, where the validation errors are reported by throwing exceptions. I'm also assuming that you are trying to collect all of the validation errors.
The simple answer is that this problem cannot be solved using this approach. To understand why, take a look at this:
boolean exceptionCaught = false;
do {
try {
item.doSomething();
} catch (MyException e) {
exceptionCaught = true;
}
} while (exceptionCaught);
This fails because each time you call item.doSomething() it is going to throw an exception at exactly the same place. The net result is an infinite loop.
The best you can do with this approach is to capture the first exception for each item in the list.
So how can you achieve what you are trying to achieve? The answer is that you have to change the validation code to use some other way to report errors than throwing exceptions. For example, you could change:
class Item {
...
void validate() {
if (noHat) {
throw new MyException("bad hat");
}
if (noPants) {
throw new MyException("world-wide pants");
}
}
}
to something like this:
class Item {
...
void isValid(List<MyException> errors) {
boolean ok = true;
if (noHat) {
errors.add(new MyException("bad hat"));
ok = false;
}
if (noPants) {
errors.add(new MyException("world-wide pants"));
ok = false;
}
return ok;
}
}
Messy huh! You could sugar this in various ways, but this style of error reporting is always going to be more complicated. But I don't think there is a practical way to avoid the messiness AND capture ALL of the validation errors.

Categories

Resources