1

Possible Duplicate:
Java exception handling

In Java, is it possible to print in console the error code line number with error information means:

try {
    // something
} catch(Exception e) {
    // modify this one to print line number of error with additional info
    System.out.println(e);
}
Community
  • 1
  • 1
Arpssss
  • 3,850
  • 6
  • 36
  • 80

5 Answers5

9

Yep.

catch(Exception e) {
    e.printStackTrace();
}

Or you could simply throw the exception, that'll also get you a stack trace.

Yuka
  • 473
  • 2
  • 10
5

Just use

e.printStackTrace();

or let the exception bubble up, if you want your program to halt on the exception.

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
4

You're probably looking for e.printStackTrace().

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
3

Note that if you don't want the complete stack trace, the Exception method getStackTrace() gives you an array of StackTraceElements. You can interrogate these for line numbers, file names etc. and generate some custom informative message highlighting the source of the exception.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
3

Throwable (which Exception extends) has a method getStackTrace() which returns a StackTraceElement[], each of which includes a method getLineNumber().

So:

e.getStackTrace()[0].getLineNumber()
amaidment
  • 6,942
  • 5
  • 52
  • 88