Can we get LineNumber and ColumnNumber in try block at which exception occured
Asked Answered
C

5

9

I have the below code with which i am able to print the fullclassname,classname,methodname, at which error occured.

Also, I am able to print Line-Number but the Line-Number printed is the line at which the variable "LineNumber" is initialized.

How can i print the exact LineNumber and ColumnNumber in try block at which error occured?

try
{
    SQL Query
}
catch(Exception e)
{
   String fullClassName = Thread.currentThread().getStackTrace()[1].getClassName();              
   String className = fullClassName.substring(fullClassName.lastIndexOf(".") + 1);  
   String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();  
   int lineNumber = Thread.currentThread().getStackTrace()[1].getLineNumber();  

     JOptionPane.showMessageDialog(null,fullClassName+"--"+className+"--"+methodName+"--"+lineNumber,"Error In Moving data from table1 to table2",JOptionPane.ERROR_MESSAGE);                         

}

Ouput:

  IPM.Shifting--Shifting--ConfirmTransfer_BActionPerformed--1138
Colombi answered 9/1, 2013 at 12:55 Comment(2)
Have you tried e.getStacktrace instead of Thread.currentThread().getStackTrace?Outbound
I tried it but not getting the required output. Output:[Ljava.lang.StackTraceElement;@fa39d7 @OutboundColombi
H
6
public class ExceptionHandler {

    /**
     * @param args
     */
    public static void main(String[] args) {

        try {
            String str = getString();
            if(str.isEmpty()){
                System.out.println("error");
            }
        } catch (Exception e) {
            StackTraceElement[] elements = e.getStackTrace();  
            for (int iterator=1; iterator<=elements.length; iterator++)  
                   System.out.println("Class Name:"+elements[iterator-1].getClassName()+" Method Name:"+elements[iterator-1].getMethodName()+" Line Number:"+elements[iterator-1].getLineNumber());
        }
    }

    private static String getString() {
        jhgfjkhgjh();
        return null;
    }

    private static void jhgfjkhgjh() {
        gfdhdfghdg();
    }

    private static void gfdhdfghdg() {
        sdfytusdgsfd();
    }

    private static void sdfytusdgsfd() {
        throw null;
    }



}
Hospice answered 13/12, 2013 at 10:21 Comment(0)
B
2
StackTraceElement[] stackTrace = Thread.currentThread()
                    .getStackTrace();
String fullClassName = stackTrace[stackTrace.length-1].getClassName();
String className = fullClassName.substring(fullClassName
        .lastIndexOf(".") + 1);
String methodName = stackTrace[stackTrace.length-1].getMethodName();
int lineNumber = stackTrace[stackTrace.length-1].getLineNumber();
Brickle answered 9/1, 2013 at 12:59 Comment(9)
The stack trace is listed from the top of the stack first.Follansbee
Its not working. Output java.awt.EventDispatchThread--EventDispatchThread--run--122. My try block starts from LineNumber:1074 and ends at LineNumber:1131 @QuoiColombi
How Shall i edit this to get the line number on which error occurs inside try block @Peter LawreyColombi
@Colombi int lineNumber = stackTrace[1].getLineNumber;Follansbee
It's not working. It gives the Line-Number at which variable lineNumber is initialized @Peter LawreyColombi
If you wanted to print the line where the exception occurred you would look at the Exception, or more normally, just print the stack trace so you can see why the error occurred.Follansbee
@peterLawrey Is it not possible to get LineNumber and ColumnNumber in try block at which exception occuredColombi
It's in the Exception, which is why this is what is usually printed. If you want to reduce it to one line (which is not a good idea IMHO) you have to search through the entires to find the one from the same method.Follansbee
@Colombi may be this will help you e.getStackTrace()[0].getLineNumber() to find exact exception line number where e is exception object.Anarch
H
2
} catch (Exception e) {            
        StackTraceElement[] stackTrace = e.getStackTrace();             
        String fullClassName = stackTrace[stackTrace.length - 1].getClassName();
        String className = fullClassName.substring(fullClassName
                .lastIndexOf(".") + 1);
        String methodName = stackTrace[stackTrace.length - 1].getMethodName();
        int lineNumber = stackTrace[stackTrace.length - 1].getLineNumber();
        JOptionPane.showMessageDialog(null, fullClassName + "--" + className + "--" + methodName + "--" + lineNumber, "Error In Moving data from table1 to table2", JOptionPane.ERROR_MESSAGE);
    }
Holdback answered 29/7, 2014 at 18:15 Comment(1)
Rather than posting just an answer, why not add an explanation of what was wrong and why?Skinflint
F
1

You could also try

JOptionPane.showMessageDialog(null, ""+Thread.currentThread().getStackTrace()[1]);

e.g.

System.out.println(Thread.currentThread().getStackTrace()[1]);

prints

Main.main(Main.java:32)
Follansbee answered 9/1, 2013 at 13:8 Comment(0)
A
0

Here , I made a solution hope It will help you .

public class TestApp{

    public static void main(String...strings){
        try{
             int num1=30, num2=0;
             int output=num1/num2;
             System.out.println ("Result: "+output);
          }
          catch(Exception e){

              ExceptionHandleCenter.throwException(e,
                      Thread.currentThread().getStackTrace()[1].getClassName(),
                      Thread.currentThread().getStackTrace()[1].getMethodName(),
                      e.getStackTrace()[0].getLineNumber());
          }
    }
}

class ExceptionHandleCenter {

    public static void throwException(Exception e, String fullClassName, String methodName,int lineNumber){

        String info = fullClassName+" method "+methodName+" at line "+lineNumber;

        if(e.getClass().equals(ArithmeticException.class)){
             System.err.println("Airthmetic exception. occurred In "+info);
         }
        if(e.getClass().equals(IllegalArgumentException.class)){
             System.err.println("Provided Argument is illegal.occurred In "+info);
         }
        if(e.getClass().equals(NumberFormatException.class)){
             System.err.println("Number Format Exception. occurred In "+info);
         }
    }
}
Anarch answered 22/3, 2018 at 11:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.