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

Akki picture Akki · Jan 9, 2013 · Viewed 9.9k times · Source

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

Answer

Prashant picture Prashant · Dec 13, 2013
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;
    }



}