Get the method name and it's contained parameters by parsing the exception

拥有回忆 提交于 2019-12-06 11:30:50

问题


When I received an exception such as IOException or RunTimeException, I can only know the line number in the class.

First of my question. Is it possible to retrieve the method name through exception? Second, is it possible to retrieve the method and the parameter of this method by line number?

p.s. I need to know the exact method name and its parameters, because I want to distinguish the overloading methods. To distinguish overloading methods, all that I know is to determine its parameters.


回答1:


try{
//your code here}
catch(Exception e){
  for (StackTraceElement st : e.getStackTrace())
  {
    System.out.println("Class: " + st.getClassName() + " Method : " 
                      +  st.getMethodName() + " line : " + st.getLineNumber());  
   }
}

as you can see in the code above, you can get the stackTrace and loop over it to get all the method names and line numbers, refer to this for more info http://download.oracle.com/javase/1.4.2/docs/api/java/lang/StackTraceElement.html




回答2:


If you look at the stacktrace you can know in which line the error occurred.

When using an overriden method you get the exact class name, source file and line number, you just have to know how to read it.

From that page:

 java.lang.NullPointerException
         at MyClass.mash(MyClass.java:9)  //<--- HERE!!!!
         at MyClass.crunch(MyClass.java:6)
         at MyClass.main(MyClass.java:3)

This says, the problem occurred in line 9 of file MyClass.java in the method mash, which was in turn invoked by the method crunch at line 6 of the same file which was invoked by main in line 3 of the same file.

Heres the source code:

 class MyClass {
     public static void main(String[] args) {
         crunch(null); // line 3
     }
     static void crunch(int[] a) {
         mash(a); // line 6 
     }
     static void mash(int[] b) {
         System.out.println(b[0]);//line 9, method mash.
     }
 }

Basically you just have to ... well read it!

Stacktraces are a bit hard to grasp the first time, but later they become a very powerful tool.

I hope this helps.



来源:https://stackoverflow.com/questions/4568437/get-the-method-name-and-its-contained-parameters-by-parsing-the-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!