Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: Pamela Baker   on Feb 11 In Java Category.

  
Question Answered By: Nicholas Wells   on Feb 11

I usually generate an Exception. This piece of code (the catch
block) very similar to a piece of code used by me at work. I hope
you find it usefull:


// Method that calls itself several times to test the Stack
void stackTraceExample(int i) {
try {
if(i<10) // If I have not executed enoght times
stackTraceExample(i+1) // I execute one more time
else
throw new Exception(); // I generate an exception
} catch(Exception ex) {
String string_error = "";
StackTraceElement stackTraceElements[] = ex.getStackTrace();

int maxLenMetodo = -1;
int maxLenClase = -1;
for(int i=0;i<stackTraceElements.length;i++) {
StackTraceElement stackTraceElement = stackTraceElements[i];
if(stackTraceElement.getMethodName().length()
>maxLenMetodo) maxLenMetodo = stackTraceElement.getMethodName
().length();
if(stackTraceElement.getClassName().length()
>maxLenClase) maxLenClase = stackTraceElement.getClassName
().length();
}

for(int i=0;i<stackTraceElements.length;i++) {
StackTraceElement ste = stackTraceElements[i];
string_error = string_error+"Class="+ste.getClassName()
+espacios(maxLenClase, ste.getClassName())+
" Método="+ste.getMethodName()
+espacios(maxLenMetodo, ste.getMethodName())+
" Archivo="+ste.getFileName()
+":"+ste.getLineNumber()+
"\n";
}
System.err.println(string_error);
}
}

Share: 

 

This Question has 1 more answer(s). View Complete Question Thread

 
Didn't find what you were looking for? Find more on Recursion with JAVA Or get search suggestion and latest updates.


Tagged: