Sunday, 25 November 2018

How to raise only one exception in python without traceback?

I wrote a method that accepts any number of arguments. If user passes nothing when calling a method, I know I will get IndexError when trying to access first element of args.

try:
    _color = args[0]
except IndexError:
    print('error')

But how to raise some other custom error, when IndexError happens, without traceback of all errors ? I only need one custom.

If I use:

try:
    _color = args[0]
except IndexError:
    raise AttributeError

I get traceback:

Traceback (most recent call last):
  File "C:/Users/...", line 12, in __init__
    _color = args[0]
IndexError: tuple index out of range

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/...", line 132, in <module>
    Brush()
  File "C:/Users/...", line 14, in __init__
    raise AttributeError
AttributeError

I just need to tell user my custom error or in this case AttributeError, without IndexError.



from How to raise only one exception in python without traceback?

No comments:

Post a Comment