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;
}
Related
In my code, I will attempt a certain task in a try-block. If exceptions are thrown, the catch-blocks will rectify the errors encountered (usually prompting for correct input). After that, the program is supposed to try again repeatedly until success is achieved. My current code is as follows:
for (bool isSuccess = false; !isSuccess;) {
try {
...
isSuccess = true;
}
// catch blocks here to correct any exceptions thrown
}
As can be seen, I'm currently using a loop structure to make the try-catch block start over if the try block fail, until the try block succeeds completely. Is there a more elegant solution?
I'd prefer to see a do loop that exits by default (then there is less chance of encountering an infinite loop). Your use of the boolean type only really mimics the behaviour of break and continue. As an alternative, perhaps more natural way, consider
do {
try {
// some code
} catch (/*whatever*/){
continue; // go again
}
break;
} while (true);
Just to give you an alternative, and if your code allows you to do so, then you could also use recursion. But in my eyes this is less favorable compared to the other ways to solve this.
public void doSomething() {
try {
...
} catch(Exception e) {
doSomething();
}
}
You can simple use a while loop.
while(!isSuccess){
try{
//DO Stuff
}
}
I think you should define a maximum of attempts. Otherwise in a worst scenario when all failures occur you app will be frozen.
You can do it with while loop
boolean isSuccess = false;
while(!isSuccess) { // loop till to isSuccess become true
try {
....
isSuccess = true;
} catch (Exception e) {
// Some Exception accrued, you can have 2 options
// 1. break the loop with break;
// 2. continue the process
}
}
You can also use recursion to do this. But I don't think it would be efficient. Do ... while would be the best approach.
Please excuse me for this kind of questions here but I am sure to get good explanation with sample which will make to have better understanding about java.
when the System.exit(0); gets executed, the system will break the execution flow and come out the system. this is what is my understanding as of now but I have came across some thing like the below :
Example 1 :
class FinallySystemExit
{
public static void main(String args[])
{
try
{
int a=2/0;
System.exit(0);
}
catch(Exception e)
{
System.out.println("i am in catch block");
}
finally
{
System.out.println("finally");
}
}
}
my understanding about the above code is it will not print anything and exit from the system but the output is :
i am in catch block
finally
Example 2
class FinallySystemExit
{
public static void main(String args[])
{
try
{
int a=2/1;
System.exit(0);
}
catch(Exception e)
{
System.out.println("i am in catch block");
}
finally
{
System.out.println("finally");
}
}
}
when i execute the above code it prints nothing
The difference between two programs are :
First Program :
int a=2/0;
and the
Second Program :
int a=2/1;
I am totally confused and my basic understanding is broken here.
Could some one explain the reason please.
Thanks
In Example 1 :
You perform int a=2/0;
This will throw java.lang.ArithmeticException as you are dividing a number by zero.
As your code is surrounded by try - catch the exception is caught and it printed the statement in catch block and went to finally block
In Example 2:
You perform int a=2/1;
So there is no problem at all.
After executing the above line, your program executed System.exit(0);. So No chance of executing the finally block. That is the reason you don't get any output in this case.
In the first snippet, there is Divide-by-zero error and so the System.exit() is not even called. In the second snippet System.exit() is called and so the JVM exited
Today at work, I had to review a code snippet that looks similar to this mock example.
package test;
import java.io.IOException;
import org.apache.log4j.Logger;
public class ExceptionTester {
public static Logger logger = Logger.getLogger(ExceptionTester.class);
public void test() throws IOException {
new IOException();
}
public static void main(String[] args) {
ExceptionTester comparator = new ExceptionTester();
try {
try {
comparator.test();
} finally {
System.out.println("Finally 1");
}
} catch(IOException ex) {
logger.error("Exception happened" ex);
// also close opened resources
}
System.out.println("Exiting out of the program");
}
}
It's printing the following output.I expected an compile error since the inner try did not have a catch block.
Finally 1
Exiting out of the program
I do not understand why IOException is caught by the outer catch block. I would appreciate if anyone can explain this, especially by citing stack unwinding process
A finally block represents a task that has to be done under both normal and abnormal conditions.
Example: You take an interview candidate to lunch. While at lunch, you find out he's wanted by the police for murder. Exception! Lunch is over, the interview is a total loss, but... you still have to pay for lunch.
try {
meetForLunch(interviewCandidate);
}
finally {
lunchBill.pay();
}
Note that paying for lunch hasn't taken care of the exception, you've still got to do something about the murderer at your interview. It's just a loose end that has to be taken care of before processing with damage control.
Most finally blocks are used in that way: A file needs to be closed whether you successfully saved the data or not, a database connection needs to be closed whether the transaction was approved or not, etc.
And the exception continues outward on its merry way, looking for a matching catch block in an enclosing scope.
Note that finally blocks will always run unless the process ends while the try block is still executing.
I think the problem is that your function
public void test() throws IOException {
new IOException();
}
Doesn't actually throw an exception - it just creates a new IOException() object. Changing this to
public void test() throws IOException {
throw new IOException();
}
should fix this.
The code above does not require much of an explanation - not definitely involving call stacks!. What is your confusion?did I miss something?
Here is my explanation
First point
You don't need both a catch and a
finally block. You can have one of
them or both of them with a
try-block, but not none of them.
The code inside the finally clause
will always be executed, even if an
exception is thrown from within the
try or catch block. If your code has
a return statement inside the try or
catch block, the code inside the
finally-block will get executed
before returning from the method.
So in the above code, an exception was never thrown (because you are not using throw in the test() method)
However, finally block got executed as promised by the the language spec and you got the output Finally 1. The next statement in the sequence of execution is the System.out.println("Exiting out of the program"); as the catch block never reached as there are no IOExceptions. So, Exiting out of the program is printed.
This question already has answers here:
Why use finally
(9 answers)
Closed 1 year ago.
As far as I can tell, both of the following code snippets will serve the same purpose. Why have finally blocks at all?
Code A:
try { /* Some code */ }
catch { /* Exception handling code */ }
finally { /* Cleanup code */ }
Code B:
try { /* Some code */ }
catch { /* Exception handling code */ }
// Cleanup code
What happens if an exception you're not handling gets thrown? (I hope you're not catching Throwable...)
What happens if you return from inside the try block?
What happens if the catch block throws an exception?
A finally block makes sure that however you exit that block (modulo a few ways of aborting the whole process explicitly), it will get executed. That's important for deterministic cleanup of resources.
Note that (in Java at least, probably also in C#) it's also possible to have a try block without a catch, but with a finally. When an exception happens in the try block, the code in the finally block is run before the exception is thrown higher up:
InputStream in = new FileInputStream("somefile.xyz");
try {
somethingThatMightThrowAnException();
}
finally {
// cleanup here
in.close();
}
You may want to put the code that you want to anyway get executed irrespective of what happens in your try or catch block.
Also if you are using multiple catch and if you want to put some code which is common for all the catch blocks this would be a place to put- but you cannot be sure that the entire code in try has been executed.
For example:
conn c1 = new connection();
try {
c1.dosomething();
} catch (ExceptionA exa) {
handleexA();
//c1.close();
} catch (ExceptionB exb) {
handleexB();
//c1.close();
} finally {
c1.close();
}
Finally always gets executed, where as your code after the catch may not.
Even though our application is closed forcefully there will be some tasks, which we must execute (like memory release, closing database, release lock, etc), if you write these lines of code in the finally block it will execute whether an exception is thrown or not...
Your application may be a collection of threads, Exception terminates the thread but not the whole application, in this case finally is more useful.
In some cases finally won't execute such as JVM Fail, Thread terminate, etc.
Still scrolling down? Here you go!
This question gave me tough time back a while.
try
{
int a=1;
int b=0;
int c=a/b;
}
catch(Exception ex)
{
console.writeline(ex.Message);
}
finally
{
console.writeline("Finally block");
}
console.writeline("After finally");
what would be printed in the above scenario?
Yes guessed it right:
ex.Message--whatever it is (probably attempted division by zero)
Finally block
After finally
try
{
int a=1;
int b=0;
int c=a/b;
}
catch(Exception ex)
{
throw(ex);
}
finally
{
console.writeline("Finally block");
}
console.writeline("After finally");
What would this print? Nothing! It throws an error since the catch block raised an error.
In a good programming structure, your exceptions would be funneled, in the sense that this code will be handled from another layer. To stimulate such a case i'll nested try this code.
try
{
try
{
int a=1;
int b=0;
int c=a/b;
}
catch(Exception ex)
{
throw(ex);
}
finally
{
console.writeline("Finally block")
}
console.writeline("After finally");
}
catch(Exception ex)
{
console.writeline(ex.Message);
}
In this case the output would be:
Finally block
ex.Message--whatever it is.
It is clear that when you catch an exception and throw it again into other layers(Funneling), the code after throw does not get executed. It acts similar to just how a return inside a function works.
You now know why not to close your resources on codes after the catch block.Place them in finally block.
Because you need that code to execute regardless of any exceptions that may be thrown. For example, you may need to clean up some unmanaged resource (the 'using' construct compiles to a try/finally block).
There may be times when you want to execute a piece of code no matter what. Whether an exception is thrown or not. Then one uses finally.
finally ALWAYS executes, unless the JVM was shut down, finally just provides a method to put the cleanup code in one place.
It would be too tedious if you had to put the clean up code in each of the catch blocks.
If catch block throws any exception then remaining code will not executed hence we have to write finaly block.
finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc.
The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).
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.