[英]how do I change what an exception does when raised?
我正在為我的操作系統類制作一個模擬的操作系統。 涉及的主題之一是中斷以及錯誤。 我將舉一個簡單的例子:
def read_instructions():
try:
with open('assembly.txt', 'r') as assembly:
for line in assembly:
status = execute_instruction(line) # this will also raise an error if instruction is invalid
except IOError as e:
raise IOError(1)
除了獲得類似[err 2] File Not Found]
東西或沿這些默認python行的東西之類的東西,我還想要更多類似這樣的東西:
def Exceptions(e):
""" this is meant to be a 'fake' event-vector table """
self.controller[status] = e # all exceptions will do this
def io_exception():
print('failed while trying to find your file')
# some traceback and logging shenanigans here
shutdown_system()
def invalid_assembly():
print('your assembly line did not follow instruction set')
# more traceback
shutdown_system()
def unimplemented():
print("you made an error I didn't catch. You've won this round.")
return {
1: io_exception,
2: invalid_assembly
}.get(e, unimplemented)()
是否可以覆蓋引發異常的位置,而將它們移到此處?
異常冒出來,直到他們碰到了except
關鍵字。 如果它們在當前執行上下文之外(也就是未捕獲 ), 則會導致Python打印堆棧跟蹤和錯誤中包含的消息(並通常終止發生在其中的線程)。
您當然可以使用自己的類擴展Exception
或任何其他標准錯誤類型,並在它們上使用raise
,但是您不能更改異常系統的工作方式,這是語言規范的一部分。
因此,您應該做的是在您的“操作系統”中, 捕獲所有異常:
try:
run_task() # Runs an OS task
except Exception as e:
# Do OS exception handling here. This will trap any exception thrown by a task.
然后執行該異常的任何操作。
您甚至可以定義自己的基本異常:
class OSBaseException(Exception):
def __init__(self, *args, **kwargs):
super(Exception, self).__init__(*args, **kwargs)
# any other init here
# An OS specific method hooks here
您希望所有用戶的異常都將擴展,從而提供OS陷阱系統期望的一些附加掛鈎。
協程和並發性好奇課程實際上提供了一個很好的例子,可以准確說明您要嘗試做的事情。
請注意,您將要壓縮所有堆棧跟蹤,這可能會讓使用操作系統的“開發人員”感到煩惱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.