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
Akki
  • 1,221
  • 3
  • 14
  • 33
  • 1
    Have you tried `e.getStacktrace` instead of `Thread.currentThread().getStackTrace`? – Fildor Jan 09 '13 at 12:59
  • I tried it but not getting the required output. Output:[Ljava.lang.StackTraceElement;@fa39d7 @Fildor – Akki Jan 09 '13 at 17:35

5 Answers5

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



}
Prashant
  • 692
  • 2
  • 11
  • 26
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();
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
  • 1
    The stack trace is listed from the top of the stack first. – Peter Lawrey Jan 09 '13 at 13:08
  • Its not working. **Output** java.awt.EventDispatchThread--EventDispatchThread--run--122. My try block starts from LineNumber:1074 and ends at LineNumber:1131 @Quoi – Akki Jan 09 '13 at 13:17
  • How Shall i edit this to get the line number on which error occurs inside try block @Peter Lawrey – Akki Jan 10 '13 at 06:02
  • 1
    @Akki `int lineNumber = stackTrace[1].getLineNumber;` – Peter Lawrey Jan 10 '13 at 08:13
  • It's not working. It gives the Line-Number at which variable lineNumber is initialized @Peter Lawrey – Akki Jan 10 '13 at 12:01
  • 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. – Peter Lawrey Jan 10 '13 at 12:05
  • @peterLawrey Is it not possible to get LineNumber and ColumnNumber in try block at which exception occured – Akki Jan 10 '13 at 14:14
  • 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. – Peter Lawrey Jan 10 '13 at 14:17
  • @Akki may be this will help you e.getStackTrace()[0].getLineNumber() to find exact exception line number where e is exception object. – ritesh9984 Mar 22 '18 at 11:52
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);
    }
  • Rather than posting just an answer, why not add an explanation of what was wrong and why? – Adam Jul 29 '14 at 18:31
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)
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
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);
         }
    }
}
ritesh9984
  • 418
  • 1
  • 5
  • 17