Exception handling practices of multiple exception throwing functions - java

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) {
...
}

Related

Java Assertion in Try with multiple catchs

Scenario:
class Assert {
public static void main(String []args) {
try {
assert false;
}
catch (RuntimeException re) {
System.out.println("In the handler of RuntimeException");
}
catch (Exception e) {
System.out.println("In the handler of Exception");
}
catch (Error ae) {
System.out.println("In the handler of Error");
}
catch (Throwable t) {
System.out.println("In the handler of Throwable");
}
}
}
I am expecting 'In the handler of Error' because AssertionError is subclass of Error but it doesn't show anything and terminate normal. after then to check the out put I added this one catch handler before Error handler .
catch (AssertionError t) {
System.out.println("In the handler of Throwable");
}
in know it's not a good practice to catch Error but if we does not need to catch why the program was not crashed it terminate normally?
By default assertions are disabled, add -ea in the command line when you execute your code with java:
java -ea Assert

Catch exceptions without a try block?

I have a lot of custom exceptions that I'm throwing in a specific cases in the code, and I'd like to have one catch block at the bottom of the method to handle them all.
All the exceptions are children of the Exception class CribbageException, so I'd like to have:
public void myMethod(){
if (whatever){
throw new CardException();
}
if (something else){
throw new InvalidCardException();
}
if (scenario 3){
throw new TwoCardsException();
}
catch (CribbageException e) {
System.out.println(e.getMessage());
}
}
But I'm getting a catch without try error.
Is there any way to use this type of exception handling?
Wrap all the throws inside a single try.
public void myMethod(){
try {
if (whatever){
throw new CardException();
}
if (something else){
throw new InvalidCardException();
}
if (scenario 3){
throw new TwoCardsException();
}
}
catch (CribbageException e) {
System.out.println(e.getMessage());
}
}

Java IO Exception handling

when I debug the below code, there is an SmbException and goes catch block line sb.append(pLogger.reportError(pStr, e));, but it does not go into the method reportError().
what is the reason behind this. please advise if any changes.
try {
sfos = new SmbFileOutputStream(sFile);
} catch (SmbException e) {
sb.append(pLogger.rError(pathStr, e));
}
below is rError() method
public String rError(String pxString,Exception e){
String errorToMailStr=null;
abcd="Verifying # "+pxString+"::Error ["+e.getMessage()+"]";
logger.debug("Error when verifying # "+pxString+":Error ["+gMsg(e)+"]");
return abcd;
}
at line logger.debug("Issue "+pxString+":Error ["+gMsg(e)+"]");
is going to below method and ends.
public abstract class ReflectiveCallable {
public Object run() throws Throwable {
try {
return runReflectiveCall();
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
Based on what you have revealed here, there is a problem in getExceptionMsg()

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 - try & catch in calling methods

I have a basic question in Java:
I have two methods: functionA & functionB. functionA calls functionB, and functionB rise an exception. The call to functionB is in try scope of functionA.
Now I also want that functionA will go to it catch scope.
There is any way to do that?
If an exception is thrown in methodB and you catch it, one way to propagate it to methodA is to rethrow it:
void methodB() throws SomeException {
try {
//Something that can throw SomeException
} catch (SomeException e) {
//rethrow e
throw e;
}
}
void methodA() {
try {
methodB();
} catch (SomeException e) {
//this block will run if methodB throws SomeException
}
}
But if you need that, you probably should not catch the exception in methodB at all and just let it propagate automatically to methodA:
void methodB() throws SomeException {
//Something that can throw SomeException: don't catch it
}
void methodA() {
try {
methodB();
} catch (SomeException e) {
//this block will run if methodB throws SomeException
}
}
Actually, that is how it works usually, provided that functionB doesn't catch the exception itself. Exceptions, when thrown, bubble up the call stack until a matching catch block is found.
Not sure if this is what you want
void functionB() throws MyException {
try{
.....
}Catch(MyException e){
//do something here;
throw e;
}
}
void functionA() {
try {
functionB();
} catch (MYException e) {
//do something else to A here
}
}

Categories

Resources