Replies: 1 comment 1 reply
-
Thanks, @hx2A. That's a great explanation (something to even include in the advanced tutorials)? |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
@marcovicci @tabreturn @villares here is the info on custom error messages.
Consider this code:
That should throw a
ZeroDivisionError
exception:What if you want to change "division by zero" to something more helpful?
You would do this:
The exception becomes:
The second parameter to
py5.register_exception_msg()
doesn't have to be a string. It can also be a callable. Maybe you want your exception message to depend on Python's exception message in some way.Now the exception becomes:
The callable feature is not that useful for this situation but it is needed for py5's type errors. Observe that the final
py5info
parameter is an empty list.Now if I change the code to this:
The exception becomes:
py5 encountered an error in your code:File "/tmp/ipykernel_180358/662210640.py", line 15, in draw 11 def draw(): 12 py5.rect(py5.mouse_x, py5.mouse_y, 10, 10) 13 14 if py5.frame_count == 300: --> 15 py5.println(foo(10)) File "/tmp/ipykernel_180358/662210640.py", line 7, in foo 6 def foo(x): --> 7 py5.stroke_weight('throw an error') 8 return x / 0 TypeError: No matching overloads found for processing.core.PApplet.strokeWeight(str), options are: public void processing.core.PApplet.strokeWeight(float) TypeError No matching overloads found for processing.core.PApplet.strokeWeight(str), options are: public void processing.core.PApplet.strokeWeight(float) [(('__init__.py',), 'stroke_weight'), (('sketch.py',), 'stroke_weight')]
You can see this is JPype's Java exception. We want to present the user with an exception that makes more sense to a Python programmer. The final
py5info
parameter contains info from the call stack that py5 can use to figure out the correct signature for the method that triggered the exception.py5 encountered an error in your code:File "/tmp/ipykernel_181414/662210640.py", line 15, in draw 11 def draw(): 12 py5.rect(py5.mouse_x, py5.mouse_y, 10, 10) 13 14 if py5.frame_count == 300: --> 15 py5.println(foo(10)) File "/tmp/ipykernel_181414/662210640.py", line 7, in foo 6 def foo(x): --> 7 py5.stroke_weight('throw an error') 8 return x / 0 TypeError: The parameter types (str) are invalid for method stroke_weight. Your parameters must match the following signature: * stroke_weight(weight: float, /) -> None
The code for that is in py5/custom_exceptions.py. Make note of
py5.reference.METHOD_SIGNATURES_LOOKUP
, which is adict
containing metadata that py5 uses for information about itself.Finally, py5 will by default remove its own nonsense from the stack trace. If you want to turn that off, you do that with this:
Beta Was this translation helpful? Give feedback.
All reactions