gasotelo gasotelo - 7 months ago 11
Java Question

Throwing an exception after retrying a block of code

Is it correct, safe and sane to throw an exception after a successful retry? Which programming principle is violated in this example?

class B {
private int total;

public void add(int amount) throws Exception {
if (amount < 0) {
throw new Exception("Amount is negative");
}
total += amount;
}
}

class A {
public B b = new B();

public void addToB(int amount) throws Exception {
try {
b.add(amount);
} catch (Exception ex) {
try {
b.add(-amount);
} catch (Exception ex2) {
}
throw new Exception("Amount was negative. It was inverted and then added.");
}

}
}

Answer

your code is working but since you are calling a addToB() method which throws exception inside a catch block you must implement another try-catch block within try-catch block. and at the end you are throwing a exception even after having so many try-catch blocks which is not good since the exceptions if not handled can cause problems and its very bad practise to throw exception if the method was success. i see that you need the user to know what happened inside the method, you can return a string from the method which will tell the user what happened inside the method.

ex: -

public String addToB(int amount){
       String msg = "";
        try{
            b.add(amount);
            msg ="successful";
        }catch(Exception ex){
            try{
                b.add(-amount);
            }catch(Exception ex2){
            }
           msg= "Amount was negative. It was inverted and then added.";
        }
 return msg;
    }

even this is not the best practise bt you might need check this.