How to make code run only if an exception was thrown? - java

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.

Related

REC_CATCH_EXCEPTION error (Exception is caught when Exception is not thrown)

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.

Exception handling practices of multiple exception throwing functions

If I have multiple functions in a function which are throwing exceptions what's the best way of handling them if they depend on each other?
With depending on each other I mean that if something throws an exceptions the code after the function which threw the exception should be skipped.
I figured out three ways to do this:
Exception nesting
public void parent() {
someFunction();
}
public void someFunction() {
try {
function1();
try {
function2();
...
} catch (Func2xception e) {
System.out.println("Function 2 failed!");
}
} catch (Func1Exception e) {
System.out.println("Function 1 failed!");
}
}
Return on exception
public void parent() {
someFunction();
}
public void someFunction() {
try {
function1();
} catch (Func1Exception e) {
System.out.println("Function 1 failed!");
return;
}
try {
function2();
} catch (Func2xception e) {
System.out.println("Function 2 failed!");
return;
}
...
}
Add exceptions to method signature
public void parent() {
try {
someFunction();
} catch (Func1Exception e) {
System.out.println("Function 1 failed!");
} catch (Func2Exception e) {
System.out.println("Function 2 failed!");
} ...
}
public void someFunction() throws Func1Exception, Func2Exception {
function1();
function2();
...
}
I sometimes use all of them together and that's a mess. Are there any good practices on how to handle situations like this?
The way to use depends on whether the exceptions should be handled by the client of the someFunction() method or else caught and handled as soon as they happen, that is, inside the someFunction() method.
In the exception nesting case, the nesting is not required.
You can use a single try statement and place the two calls that may generate the exceptions in it.
If an exception occurs in one of the two invoked methods, you finish in one of the catch statements and so the second method is executed only if the first one has not thrown the caught exception.
It produces exactly the same result than your code but with a single try and without nesting that is less readable.
public void someFunction() {
try {
function1();
function2();
...
} catch (Func1Exception e) {
System.out.println("Function 1 failed!");
}
catch (Func2xception e) {
System.out.println("Function 2 failed!");
}
}
This way of doing is suitable if you have some other instructions after the catch statements and you want them to be executed even if one of the expected exceptions was caught.
The return on exception case manifests a close enough problem.
It may be refactored with a single try :
public void someFunction() {
try {
function1();
function2();
...
} catch (Func1Exception e) {
System.out.println("Function 1 failed!");
return;
}
catch (Func2xception e) {
System.out.println("Function 2 failed!");
return;
}
}
...
}
This way of doing is suitable if you have some other instructions after the catch statements and you don't want them to be executed if one of the expected exceptions was caught.
Nevertheless for these two cases, if the exception handling is the same for the two exceptions (Func1Exception and Func2xception), you could group them in a single catch statement :
public void someFunction() {
try {
function1();
function2();
...
}
catch (Func1Exception | Func2xception e) {
System.out.println("Function 1 or 2 failed!");
}
}
At last, the add exceptions to method signature case makes sense only if the exceptions should be handled by the client of the method.
You can catch multiple exceptions in one catch clause, starting from Java 7 I believe.
try {
...
} catch(IOException | IllegalArgumentException | SomeOtherException e) {
...
}

Android / Java: how to define a code block and leave it without custom exceptions?

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;
}
}

Java Do X IF catch was not called from a try loop

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.

Embedding try-catch blocks within try-catch blocks in Java

Let's say I have method a() and method b() which both may throw an exception. In my program, there is a situation where I have to call at least one of them; it doesn't matter which I call. However, if one of them throws an exception, I have to call the other one. If they both throw an exception, I don't have to do anything.
I was thinking of doing something like this:
try {
a();
catch (Exception e) {
try {
b();
catch (Exception e) {
}
}
but I thought this would be impractical if I had more than two methods to call. So I was wondering if there were a more elegant or better way to do something I'm trying to do.
you can
abc:
{
try
{
a();
break abc;
}
catch(Exception e){}
try
{
b();
break abc;
}
catch(Exception e){}
try
{
c();
break abc;
}
catch(Exception e){}
}
if the chain is even longer, probably better
for(int i=0; i<4; i++)
{
try
{
switch(i)
{
case 0: a(); break;
case 1: b(); break;
case 2: c(); break;
case 3: d(); break;
}
}
catch(Exception e){} // next
}
You can return after each case, such that after the first success, a return is hit.
public void uponSuccessStop() {
try {
a();
return;
} catch (Exception e) {}
try {
b();
return;
} catch (Exception e) {}
try {
c();
return;
} catch (Exception e) {}
}
Another option would be to throw out exceptions, and use short-circuit boolean logic:
public boolean tryA() {
try {
a();
return true;
} catch (Exception e) {
return false;
}
}
// repeat for B and C
public void uponSuccessStop() {
boolean succeeded = tryA() || tryB() || tryC();
}
It is difficult to discuss practical options at such a level of generality, but you could do something like this:
boolean succeeded = false;
try {
a();
succeeded = true;
} catch (Exception e) {
// intentional ...
}
if (not succeeded) {
try {
b();
catch (Exception e) {
...
}
}
... and all sort of other arrangements where you use conditionals (or break or return) to avoid the nesting.
But whether they are more "elegant" ... or more readable ... will be highly context dependent. And also dependent on the reader. (As an experienced Java programmer, I have no difficulty understanding nested exceptions. In my experience, artificial constructions that are intended to avoid nesting can result in code that is harder to read / understand.)
I hope that you are not really going to catch Exception ... 'cos if you are, that is a much worse problem than than nesting of try / catch!!

Categories

Resources