How to get error line number using try/catch in java?

Viewed 7527

I want to find out the error line number using try and catch. I tried to get some information from How to get error line number of code using try-catch, but it didn't help since I use different language.

Now, I am getting java.lang.NumberFormatException: For input string: "" when I do

try {
    // My Code Here

} catch(Exception e) {
      System.out.println(e);
}

I tried printing e.getStackTrace()[0].getLineNumber()); as well, but it seems like it's not showing the correct error line number. Is there any way I can get it easily? I have a pretty big file and I don't think I'll be able to go over line by line to figure out what's wrong.

Thanks!

2 Answers
package com.ms.common;

public class Run {

public static void main(String[] args) {
try {

  int value = 5;
  int divider = 0;

  int result = value / divider;

} catch (Exception e) {
  System.out.println(e.getStackTrace()[0]);
}

}

}

Error at Run.java at line# 11

com.ms.common.Run.main(Run.java:11)

If you use a Logger library, it can print the stack trace in debug mode that points to the line number. else printStackTrace() is your friend.

try {
    // My Code Here

} catch(Exception e) {
      System.out.println(e);
      e.printStackTrace();  // This will give line number
}
Related