Is there any way I can declare a custom exception class where I don't need to use try and run or decorators over and over? where it can catch errors itself just like the built-in KeyboardInterrupt class. Example:
def keyboard_err(func):
def checking(*args, **kwargs):
try:
return func(*args, **kwargs)
except KeyboardInter forrupt:
pass
return checking
class site():
def __init__(self, link: str):
self.link = link
@keyboard_err
def search(self): ...
@keyboard_err
def check_url(self): ...
@keyboard_err
def site_info(self, name: bool = False): ...
@keyboard_err
def write_url(self, url, type='w'): ...
@keyboard_err
def parse(self): ...
@keyboard_err
def custom_command(com): ...
@keyboard_err
def exclude_command(com): ...
Edit: Instead of adding the decorator again and again Can I just use a custom exception that will return a custom message by itself when the KeyboardInterrupt exception raised
CodePudding user response:
You can define your own exceptions by inheriting from the builtin Exception
class:
>>> class MyCustomException(Exception):
... pass
...
Which will have behaved in the same way as the base exception class. I.e. can be raised, try/catched, produces tracebacks and results in a sysexit with status 1:
>>> raise MyCustomException
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.MyCustomException
And:
>>> try:
... raise MyCustomException
... except MyCustomException:
... print('An error occured')
...
An error occured
On your example. Is there any good reason why you want to catch KeyboardInterrupt everywhere?
CodePudding user response:
You wrote half the code. And as Michal Racko said, just creating a custom exception would help.
import sys
# To remove tracebacks. If you want them, then comment this line.
sys.tracebacklimit = 0
# Custom Exception Class
class OperationFailed(Exception):
def __init__(self, message: object):
self.message = message
super().__init__(self.message)
def keyboard_err(func):
def checking(*args, **kwargs):
print("in decorator")
try:
return func(*args, **kwargs)
except KeyboardInterrupt:
raise OperationFailed("You have cancelled the operation") from None
except Exception as e:
print(e)
return checking