java - Throwing an exception after retrying a block of code -


is correct, safe , sane throw exception after successful retry? programming principle violated in example?

class b {     private int total;      public void add(int amount) throws exception {         if (amount < 0) {             throw new exception("amount negative");         }         total += amount;     } }  class {     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 negative. inverted , added.");         }      } } 

your code working since calling addtob() method throws exception inside catch block must implement try-catch block within try-catch block. , @ end throwing exception after having many try-catch blocks not since exceptions if not handled can cause problems , bad practise throw exception if method success. see need user know happened inside method, can return string method tell user happened inside 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 negative. inverted , added.";         }  return msg;     } 

even not best practise bt might need check this.


Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -