Sumit Shrestha
Sumit Shrestha

Reputation: 919

To find line number where exception was thrown in java/grails

I have to write logic for detecting what line of code was exception thrown so we can go fix that issue later. The exception object's getStackTrace() gives us a list of stacktrace each with level. I am not interested in getting lowest place where exception was thrown but rather my class method which was responsible in passing parameters. Here is an example of what i am asking

class Test {
    void divide() {
    try{
        float i = 1/0
    }
    catch(Exception e){
        def v = e.getStackTrace()[0]
        println v.getClassName()
    }
    }
}

This would print class java.math.BigDecimal but i am interested in getting Test class so i can go to it's divide and fix this bug. Now, Test appears in some nth line which i cannot know in run time. One approach would be to iterate stacktrace list and try finding class which is custom developed but how to detect that? Or if there is some library function that already does that it would be great.

Upvotes: 1

Views: 687

Answers (1)

Igor Artamonov
Igor Artamonov

Reputation: 35961

Try this:

println e.stackTrace.find {
  it.className == 'Test' && it.methodName == 'divide'
}

Or, I guess you want to check all levels of stacktrace, then:

Throwable t = e
StackTraceElement found = null
while (!found && t) {
  found = e.stackTrace.find {
    it.className == 'Test' && it.methodName == 'divide'
  }
  t = e.cause
}
println found

Upvotes: 2

Related Questions