What is the behavior of catch block, if it is not at the end of the block.
private Boolean connect(String addr) {
.....
try {
connected = true;
} catch (ExceptionType name) {
//log // print stack trace etc, but no explicit return
} catch (ExceptionType name) {
}
if (some_other_condn) {
..
}
}
Do one need return inside catch block if I don't want to execute rest of the code in the block?
Yes you do need to return from the catch block if you don't want to execute rest of the code.
Or, better just put the rest of the code within the try block itself.
try {
connected = true;
if (some_other_condn) {
//...
}
} catch (ExceptionType name) {
//log // print stack trace etc, but no explicit return
} catch (ExceptionType name) {
}
Yes, that is correct. If you don't want to execute rest of the code, you need to return (But you will be returned on exception case only, I hope you know about that). Success case your return statement won't execute.
Related
I have a function which consists of a while loop.
Inside the while loop, I call a number of private methods.
If any of the methods fails (returns false, but also throws a private designed exception), I would like to continue strait to the next iteration.
example:
void func (){
while (true){
func1();
func2();
func3();
}
}
As I said, each func also throws myException object on error.
Thank you!
Wrap each function() call with a try-catch block. Like
while(true){
try{
func1();
}catch(YourException1 exception){
//Do something.
}
try{
func2();
}catch(YourException2 exception){
//Do something.
}
try{
func3();
}catch(YourException3 exception){
//Do something.
}
}
Put a try-catch block inside the loop.
Catch the exception and decide what to do:
void func (){
while (true){
try {
func1();
} catch (MyException e) {
// print error or don't do nothing
}
try {
func2();
} catch (MyException e) {
// print error or don't do nothing
}
try {
func3();
} catch (MyException e) {
// print error or don't do nothing
}
}
}
You could use the && operator to connect the function calls to not execute any after one of them failed and surround everything with a try-catch block.
void func (){
while (true){
try{ func1() && func2() && func3(); }
catch (YourCustomException e){ }
}
}
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;
}
}
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.
I have a try with several different catches after it. I have some "cleanup" code that only should be run if there was an exception thrown. I could add the same code to each exception, but that becomes a maintenance nightmare. Basically, I'd like something like the finally statement, but for it to only run if an exception was thrown.
Is this possible?
There is no direct support for this unfortunately. How about something like this
boolean successful = false;
try {
// do stuff
successful = true;
} catch (...) {
...
} finally {
if (!successful) {
// cleanup
}
}
The only thing I can think of is to set a variable in each catch and then check for that variable in finally.
Pseudocode:
Boolean caught = false;
try {
//risky code here
catch(err) {
caught = true;
// Do other stuff
}
catch(err) {
caught = true;
// Do other stuff
}
catch(err) {
caught = true;
// Do other stuff
}
finally {
if (caught) {
// Do clean up
}
}
I could add the same code to each exception, but that becomes a maintenance nightmare.
Or if you blot out the 'exception':
I could add the same code to each [place], but that becomes a maintenance nightmare.
This is what methods are made for.
private void cleanup() { /* clean up */ }
...
try {
// oh noes
} catch (MyException me) {
cleanup();
} catch (AnotherException ae) {
cleanup();
}
Maintenance hassle gone!
Why don't you just use simple try & catch?
try
{
foo();
}
catch(Exception1 e1)
{
dealWithError(1);
}
catch(Exception2 e2)
{
dealWithError(2);
}
catch(Exception3 e3)
{
dealWithError(3);
}
...
private void dealWithError(int i)
{
if(i == 1) // deal with Exception1
else if(i == 2) // deal with Exception2
else if(i == 3) // deal with Exception3
}
You could try wrapping two layers of exception handlers, and rethrow the exception after you have done the common handling:
try {
try {
// your code goes here
} catch (Throwable t) {
// do common exception handling for any exception
throw t;
}
} catch (NullPointerException nx) {
// handle NPE
} catch (Throwable t) {
// handle any other exception
}
Not sure I really like this solution though... feels like a bit of a hack. I'd probably rather see the Exception explicitly handled in each instance, even if this means repeating a call to some kind of shared cleanup function.