Not sure if this has already been answered, but.
I know that in java there is the try, catch and finally blocks, but is there one which is only called if try has no errors/exceptions?
Currently after stating the command that needs to be run, I'm setting a boolean to true, and after the try and catch block, the program checks for if the boolean is true.
I'm pretty sure that there is a much simpler way, help is appreciated!
Just put your code after the try...catch block and return in the catch:
boolean example() {
try {
//dostuff
} catch (Exception ex) {
return false;
}
return true;
}
This would also work if you put the return true at the end of the try block as the code would jump to the catch on error and not execute the rest of the try.
void example() {
try {
//do some stuff that may throw an exception
//do stuff that should only be done if no exception is thrown
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
No, there is no block called only if no exceptions were raised.
The catch block is called if there were exceptions, finally is called regardless.
As stated, you can emulate such a beast with something like:
bool completed = false;
try {
doSomeStuff();
completed = true;
} catch (Exception ex) {
handleException();
} finally {
regularFinallyHandling();
if (completed) {
thisIsTheThingYouWant();
}
}
but there's nothing built into the language itself that provides this functionality.
Related
Basically i have 2 different commands i could possibly execute. If the first one does not work, I want to execute the second command.
Is there some easier, cleaner way to do this?
What would i even put in the if statement?
try
{
// code that may throw an exception
driver.findElement(By.id("component-unique-id-31")).click();
}
catch (Exception ex)
{
// Print to console
}
if(previous command threw an exception){
try
{
//Another command i want executed if the above fails
driver.findElement(By.xpath("//h3[normalize-space()='Something']")).click();
}
catch (Exception ex)
{
// handle
}
}
You can put the second command inside the catch block of the first try-catch, as following:
try
{
// code that may throw an exception
driver.findElement(By.id("component-unique-id-31")).click();
}
catch (Exception ex1)
{
try
{
//Another command i want executed if the above fails
driver.findElement(By.xpath("//h3[normalize-space()='Something']")).click();
}
catch (Exception ex2)
{
// handle
}
}
You can wrap up both the try-catch{} blocks within a single try-catch-finally{} block as follows:
try {
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.id("component-unique-id-31"))).click();
System.out.println("Within in try block.");
}
catch(TimeoutException e) {
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//h3[normalize-space()='Something']"))).click();
System.out.println("Within in catch block.");
} finally {
System.out.println("The 'try catch' is finished.");
}
PS: You must avoid catching the raw exception.
public function() {
try {
// execute code and if error jump into 1st catch
return output;
} catch (Exception e){
//execute code and if error jump in 2nd catch
return output1
} catch (Exception e){
//execute code and stop
return output 2
}
}
The Above is the Code flow I want to achieve, I wanted to check if there is way or better way to do my scenario where I want to try a piece of code and if it fails, catch and execute first catch piece of code and if it again fails and exception occurs in first catch also go for final piece of code in last catch. Any help is very much appreciated. Thanks in advance.
Here is the flow I want to achieve :
try ----if error/exception----> catch1 ----if error/exception----> catch2
You can't do that. To catch a exception inside a catch block you should user another try/catch.
public function() {
try {
return output;
} catch (Exception e){
try {
return output1;
} catch (Exception e2) {
return output2;
}
}
}
I am seeing a weird behaviour where I added some code inside a try block and now I am getting the spotbug error REC_CATCH_EXCEPTION (Exception is caught when Exception is not thrown) for some reason.
So basically originally, my code was something like this:
while (true) {
try {
if (something()) {
doSomething();
} else if (somethingElse()) {
doSomethingElse();
} else {
do();
}
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
And when I run the code above, I do not get any spotbug errors. However when I add the new else if block I get the REC_CATCH_EXCEPTION error. So my new code, where I am seeing the error, is something like this:
while (true) {
try {
if (something()) {
doSomething();
} else if (somethingElse()) {
doSomethingElse();
} else if (someOtherThing()) {
doSomeOtherThing();
} else {
do();
}
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
Nothing really changed other than the addition of the doSomeOtherThing() method. So I am not exactly sure why I am seeing this error. Also, please note that the doSomeOtherThing() method does not throw or catch any exceptions inside of it.
I know how try, catch & finally work (for most part), but I have one thing I was wondering: what happens with a return statement after a try-catch-finally, while we already had a return in the try (or catch)?
For example:
public boolean someMethod(){
boolean finished = false;
try{
// do something
return true;
}
catch(someException e){
// do something
}
finally{
// do something
}
return finished;
}
Let's say nothing went wrong in the try, so we returned true. Then we will go to the finally where we do something like closing a connection, and then?
Will the method stop after we did some stuff in the finally (so the method returned true in the try), or will the method continue after the finally again, resulting in returning finished (which is false)?
Thanks in advance for the responses.
The fact that the finally block is executed does not make the program forget you returned. If everything goes well, the code after the finally block won't be executed.
Here is an example that makes it clear:
public class Main {
public static void main(String[] args) {
System.out.println("Normal: " + testNormal());
System.out.println("Exception: " + testException());
}
public static int testNormal() {
try {
// no exception
return 0;
} catch (Exception e) {
System.out.println("[normal] Exception caught");
} finally {
System.out.println("[normal] Finally");
}
System.out.println("[normal] Rest of code");
return -1;
}
public static int testException() {
try {
throw new Exception();
} catch (Exception e) {
System.out.println("[except] Exception caught");
} finally {
System.out.println("[except] Finally");
}
System.out.println("[except] Rest of code");
return -1;
}
}
Output:
[normal] Finally
Normal: 0
[except] Exception caught
[except] Finally
[except] Rest of code
Exception: -1
If all goes well, return inside the try is executed after executing the finally block.
If something goes wrong inside try, exception is caught and executed and then finally block is executed and then the return after that is executed.
In that case the code inside the finally is run but the other return is skipped when there are no exceptions.
You may also see this for yourself by logging something :)
Also see this concerning System.exit:
How does Java's System.exit() work with try/catch/finally blocks?
And see returning from a finally:
Returning from a finally block in Java
public int Demo1()
{
try{
System.out.println("TRY");
throw new Exception();
}catch(Exception e){
System.out.println("CATCH");
}finally{
System.out.println("FINALLY");
}return 0;
}
the output of call to this method is like this
TRY
CATCH
FINALLY
0
Means Consider Try{}catch{}finally{} as sequence of statements executed one by one In this particular case.
And than control goes to return.
Definitely the code inside try will execute.. but when it reaches to return statement.. it will move to the finally block without executing the return statement in try block.. and then the code of finally will be executed and then the return statement of try will execute.
I seem to be stuck with a very simple task that would require GOTO statements and, in my opinion, would justify a use of those.
I have the very simple task to exit a void on different conditions. Within its code, several dozen operations are being done and most of them can fail. I test them with try {}.
Now, based on the criticality of the operation, I either need to exit immediately and do nothing else, or, I just need to interrupt control flow and jump to a final point to do some cleaning up and then exit the method.
MWE:
public void myMethod () {
try { op1(); } catch (Exception e) { return; } // Fail here: exit immediately
try { op2(); } catch (Exception e) { cleanUpFirst(); return; } // Fail here: do Cleaning up first, then exit
try { op3(); } catch (Exception e) { return; } // Fail here: exit immediately
try { op4(); } catch (Exception e) { cleanUpFirst(); return; } // Fail here: do Cleaning up first, then exit
try { op5(); } catch (Exception e) { cleanUpFirst(); return; } // Fail here: do Cleaning up first, then exit
// ....
}
public void cleanUpFirst() { /* do something to clean up */ }
For code readability, I'd like to a) avoid a separate function and b) do not have more than one statement within the catch block; it just blows up the code. So, in my opinion this would perfectly justify the use of a GOTO statement.
However, the only solution I came up with, given that only two outcomes are possible, is this:
public void myMethod () {
do {
try { op1(); } catch (Exception e) { return; }
try { op2(); } catch (Exception e) { break; }
try { op3(); } catch (Exception e) { return; }
try { op4(); } catch (Exception e) { break; }
try { op5(); } catch (Exception e) { break; }
// ....
} while (1==0);
/* do domething to clean up */
}
Yes, I have heard of exceptions and that is is the Java way. Is that not as overkilled as using the separate void? I do not need the specifics, I simply need a yes/no result from each operation. Is there a better way?
why not
boolean cleanupfirst = false;
try {
op1 ();
cleanupfirst = true;
op2 ();
cleanupfirst = false;
op3 ();
} catch (Exception e) {
if (cleanupfirst)
cleanup ();
return;
}
You're over-thinking it.
4 minor adjustments.
Let Opn() return a boolean for success or failure, rather than throwing an Excpetion.
Let CleanupFirst handle program termination (you can rename it to clean exit if you want). The new parameter passed to CleanExit is the System.exit code.
Use System.Exit to return a proper return code to the OS, so you can use it in scripting.
It does not seem like your program has a successful path.
if (!op1())
System.exit(1); // <- send a failed returncode to the OS.
if(!op2())
cleanExit(2);
if (!op3())
System.exit(3); // <- send a failed returncode to the OS.
if (!op4())
cleanExit(4);
if (!op5())
cleanExit(5);
cleanExit(0);
More methods for better readability:
public void myMethod() {
try {
tryOp1();
tryOp2();
...
} catch(Exception ignore) {}
}
public void tryOp1() throws Exception {
op1();
}
public void tryOp2() throws Exception {
try {
op1();
} catch (Exception e) {
cleanUp();
throw e;
}
}