In Java catch block, how do you know which method/line throws the exception? -
in try block, want execute 2 functions. if first 1 failed don't execute second. want print out function failed.
see following code.
try { = func1(); b = func2(); //won't execute if failed } catch (exception e) { //todo: print or b failed? }
does language support scenario naturally?
if not, following practice? (i cannot think of wrong it. concerns me don't remember seeing 1 using return
in catch
.)
try { = func1(); } catch { //print: failed return; //if failed skip execution of b } try { b = func2(); } catch { //print: b failed }
edit: summary of comments:
throw different exception 2 methods.
- in case methods written others , have no control.
e.printstacktrace() print line number , function
- i want more printing. more like, if failed, execute following code.
what want string methodname = e.getstacktrace()[0].getmethodname());
but hardly practice. standard way log exception using appropriate method in logging framework or (if writing console app, case java) print error or standard output or optionally other printstream
, example using printstacktrace(printstream)
.
but in cases want propagate exception upper layers , handle (or decide not handle it) appropriate high level code. catching exceptions leads nasty bugs. returning catch black bad idea in 99% of cases because exception signalizes abnormal termination of method while returning value not.
Comments
Post a Comment