1

I catch the following code in a try/catch statement:

            catch (Exception e){
            Log.d("MyTag", "exception ->: "+e.toString());
        }

It prints:

MyTag: exception ->: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference

How can I make it print the line number along with the error message because I am finding it difficult to locate this null object reference string within my code?

user3560827
  • 632
  • 1
  • 5
  • 22

2 Answers2

2

The simplest solution is to rewrite your Log statement as:

Log.d("MyTag", "Exception while doing ...", e);

(where you replace the "..." with a few words about what the try block was trying to do)

This will print a complete stack trace, along with your two strings, to LogCat.

The vast majority of Android developers go this route and should go this route.

If, for some reason, you really want to just get the line number, e.getStackTrace()[0].getLineNumber() should have that information. However, in many cases, that will not be a line number in your Java file, but a line number in some other Java file where the exception occurred. This is why printing the stack trace is a better option, as you get more files and line numbers.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
1

Use the method with the Throwable at the end:

catch (Exception e){
            Log.d("MyTag", "exception ->:", e);
}

Log Api

Juan
  • 5,525
  • 2
  • 15
  • 26