java - How to determine the origin of a thrown exception without writing a try/catch for each statement? -
i wondering if possible without writing try/catch block every single call. want able tell method threw exception can handle them differently. consider following 2 (fairly identical) methods:
public void setbranchid(string id) throws numberformatexception{ if(id.trim().length() != 0 && id != null){ try{ branchid = integer.parseint(id); }catch(numberformatexception ex){ outputfunc.printerror(ex); //prints stack trace console throw ex; } } else{ branchid = null; } } public void setcashonhand(string cash) throws numberformatexception{ if(cash.trim().length() != 0 && cash != null){ try{ cashonhand = double.parsedouble(cash); }catch(numberformatexception ex){ outputfunc.printerror(ex); throw ex; } } else{ cashonhand = null; } }
what want do:
try{ setbranchid(string1); setcashonhand(string2); //other methods }catch(numberformatexception ex){ if(/*exception came setbranchid*/){ //code } else if(/*exception came setcashonhand*/){ //code } }
you not need create new exception (even though nicer) can change message returns exception :
public void setbranchid(string id) throws numberformatexception{ if(id.trim().length() != 0 && id != null){ try{ branchid = integer.parseint(id); }catch(numberformatexception ex){ outputfunc.printerror(ex); //prints stack trace console throw new numberformatexception("setbranchid error : " + ex ); } } else{ branchid = null; } }
then can exception message if starts setbranchid:
try{ t.setbranchid("xxx"); t.setcashonhand("xxx"); //other methods } catch (numberformatexception ex){ if (ex.getmessage().startswith("setbranchid")) { system.out.println("error setbranchid method"); } ..... }
Comments
Post a Comment