Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 764
Akki Avatar asked Jan 09 '13 12:01

Akki


1 Answers

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;
    }



}
like image 112
Prashant Avatar answered Sep 18 '22 13:09

Prashant