How to retrieve where an error happens

edited January 2018 in How To...

I get an error message that I wrote myself in a method, but I can't figure out in which centext it happens.

Example :

void aMethod() {
 if(problem){print("Error");}
}

The method aMethod is used in a lots of different contexts in my sketch. How can I modify my error message so I get something like the stack trace of an error ?

Answers

  • You can use exceptions for this.

    If you want to pass an error up the stack:

    if(problem){
       throw new Exception("Error");
    }
    

    If you just want to print a stack trace:

    if(problem){
      new Exception().printStackTrace();
    }
    

    Shameless self-promotion: I wrote a tutorial on Exceptions available here.

  • What id your definition for problem? You get access to the stack when an error is thrown. However, how to merge your approach with:

    try {
        .....
    } 
    catch (IOException e) {
      e.printStackTrace();
    }
    

    More info is needed.

    Kf

  • edited January 2018

    first idea

    you can make a different println statement in every place that aMethod() is called

    println ("I am line number 93 calling aMethod()");
    aMethod(); 
    

    second idea

    OR you can pass an ID (or a String) to aMethod():

    void aMethod(int ID) {
         if(problem) { 
            print("Error: " + ID);
        }
     }
    
  • @KevinWorkman the first solution gives me an Unhandled exception type Exception. The second doesn't print anything but looks to me like what I'm looking for.

    @kfrajer the true situation is :

    Real divide(Real A, Real B) { // divide A by B
      if(B.isZero()){print("Error");}
      else{...}
    }
    

    For a homemade class Real

    @Chrisir I'll use this as a last resort if I can't find something easier to handle

  • That is what I would expect the first solution to do. You need to handle the exception. Please read the link on exceptions I posted above.

    The second solution should print a stack trace to your console, unless you're immediately exiting or something. Please post a MCVE showing exactly what you tried.

  • Problem solved, new Exception().printStackTrace(); did it ! I realized that I wrote the same error message in another line in the same method, and it was this other one that was written in the console. Thanks !

Sign In or Register to comment.