[英]How can I define a custom exception class that will only print 'Operation Cancelled' on KeyboardInterrupt instead of raising exception
有什么方法可以声明一个自定义异常 class ,我不需要一遍又一遍地使用 try and run 或装饰器? 它可以自己捕获错误,就像内置的 KeyboardInterrupt class 一样。 例子:
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): ...
编辑:而不是一次又一次地添加装饰器我可以只使用一个自定义异常,它会在引发 KeyboardInterrupt 异常时自行返回一条自定义消息
您可以通过从内置Exception
class 继承来定义自己的异常:
>>> class MyCustomException(Exception):
... pass
...
其行为方式与基本异常 class 相同。 即可以引发、尝试/捕获、产生回溯并导致状态为 1 的 sysexit:
>>> raise MyCustomException
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.MyCustomException
和:
>>> try:
... raise MyCustomException
... except MyCustomException:
... print('An error occured')
...
An error occured
以你为例。 你有什么充分的理由要到处捕捉 KeyboardInterrupt 吗?
你写了一半的代码。 正如 Michal Racko 所说,创建一个自定义异常会有所帮助。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.