Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java catch block, how do you know which method/line throws the exception?

In try block, I want to execute two functions. If the first one failed then don't execute the second. I also want to print out which function failed.

See following code.

try {
  a = func1();
  b = func2();  //won't execute if a failed
}
catch (Exception e) {
  //TODO: print a or b failed?
}

Does the language support this scenario naturally?

If not, is the following a good practice? (I cannot think of anything wrong about it. But it concerns me as I don't remember seeing any one using return in catch.)

try {
  a = func1();
}
catch {
  //print: a failed
  return; //if a failed then skip the execution of b
}

try {
  b = func2();
}
catch {
  //print: b failed
}

EDIT: Summary of comments:

  1. throw different exception from two methods.

    • In this case the methods are written by others and I have no control.
  2. e.printStackTrace() will print line number and function

    • I want to do more than just printing. More like, if a failed, execute the following code.
like image 226
Weishi Z Avatar asked Jan 16 '16 00:01

Weishi Z


1 Answers

What you want is String methodName = e.getStackTrace()[0].getMethodName());

But this is hardly a good practice. The standard way is to log the exception using appropriate method in your logging framework or (if writing a console app, which is rarely the case with Java) to print it to the error or standard output or optionally to other PrintStream, for example using printStackTrace(printStream).

But in most cases you want to propagate exception to the upper layers and handle (or decide to not handle it) by the appropriate high level code. Catching exceptions like this leads to nasty bugs. Returning from catch black is also a very bad idea in 99% of cases because exception signalizes abnormal termination of the method while returning a value does not.

like image 90
ps-aux Avatar answered Oct 01 '22 08:10

ps-aux