Originally posted by vijay malhotra:
There was some problem at javaranch site and I was unable
see the reply to my post regarding exceptions so I am
posting it again so please reply again
If an exception is thrown from a particular block
then from corresponding exception handling catch block is it
possible to transfer the control block back to the block from
where exception was thrown ?
Is it possible with the help of continue statement
in the exception handling block for ex
continue grace;
where grace is the label defined in the block from
where the exception was thrown ?
If the answer is Yes then please explain with help of
an example and if answer is No then please explain
why it's not possible.
Hello Vijay,
Yes! It is posible to get back where the exception was thrown. Here is the code that throw an exception:
public class Demo
{
public static void main(
String[] args) {
try {
// here is the line of code you want to get back
System.out.println("In try block");
// here is where Exception is thrown.
// This throw is intention, but your code might
// throw an Exception based on different logic
throw new Exception();
}
catch(Exception e) {
System.out.println("Exception caught in main");
}
}
}
This code wiill print:
"In try block"
"Exception caught in main"
The following code will allow you to get back to the line of code before the Exception occurs. Note that the use of 'eflag' to bypass the intentional throw statement. In your code, this flag might not be needed since you will have a new chance to alter the logic to prevent Exception from occuring.
--------------- The new program --------------------------------
public class Demo
{
public static void main(String[] args) {
boolean eflag = false; // needed in this code to alter logic
boolean blfag = false; // break flag to get out of for loop
Outer: // re-entrance point
for(;;) {
try {
// here is the line of code you want to get back
System.out.println("In try block");
// here is where Exception is thrown
if (false == eflag) {
throw new Exception();
}
else
System.out.println("No more Exception");
bflag = true; // no Exception - ready to break
}
catch(Exception e) {
eflag = true;
System.out.println("Exception caught in main");
continue Outer;
}
if (true == bflag) break;
}
}
}
This code wiill print:
"In try block"
"Exception caught in main"
"In try block"
"No more Exception"
Hope that helps,
Lam