Reputation: 165
Hello in my java class Toto, I have 3 static methods I would like to know when I'm in one of these methods , how to get and display the name of package.class.methode in the try catch bloc ? I tried in methodeA:
public static void methodeA(){
try{
system.out.println("I do something");
}
catch(Exception e){
system.out.println("failed" +e.getClass().getMethods().toString());
}
but it is not working, how also could I show it in try ? thanks
Upvotes: 3
Views: 2887
Reputation:
If you throw the exception, is affecting your performance. Is not needed throw the exception,
public class AppMain {
public static void main(String[] args) {
new AppMain().execute();
}
private void execute(){
RuntimeException exception = new RuntimeException();
StackTraceElement currentElement = exception.getStackTrace()[0];
System.out.println(currentElement.getClassName());
System.out.println(currentElement.getMethodName());
}
}
Upvotes: 0
Reputation: 11
You can use the example below:
public class A
{
public static void main(String args[])
{
new A().intermediate();
}
void intermediate()
{
new A().exceptionGenerator();
}
void exceptionGenerator()
{
try
{
throw new Exception("Stack which list all calling methods and classes");
}
catch( Exception e )
{
System.out.println( "Class is :" + e.getStackTrace()[1].getClassName() +
"Method is :" + e.getStackTrace()[1].getMethodName());
System.out.println("Second level caller details:");
System.out.println( "Class is :" + e.getStackTrace()[2].getClassName() +
"Method is :" + e.getStackTrace()[2].getMethodName());
}
}
}
Upvotes: 1
Reputation: 597382
e.printStackTrace();
- that will print the whole exception stracktrace - i.e. all the methods + line numbers.
Upvotes: 1
Reputation: 89199
The preferred option.....
catch(Exception e) {
e.printStackTrace();
}
or (not a wise option since you don't know what exception is thrown an you have no Stack Trace Elements printed).
catch(Exception e) {
System.out.println(e.getStackTrace()[0].getMethodName());
}
Upvotes: 0
Reputation: 22308
Have ou noticed you already have the information in your exception's stacktrace ?
Indeed, Exception class provides a getStackTrace()
method that returns you an array of StacktraceElement. Each of these elements gives you class name, method name, and some other details. What you can do is look in this array if you find one of your three methods, and voila !
However, be warned that detection of method name may fail if you use an obfuscator on your code.
Upvotes: 0