我已经在python中编写了一个脚本,除了处理所有运行时异常的处理(catch块)之外。如果我把try块放在与脚本相同的文件中,那么它打印异常但我需要的是try块是在另一个文件中,然后是它将使用脚本中编写的catch块的过程。
import traceback
import sys
import linecache
try:
# execfile(rahul2.py)
def first():
second()
def second():
i=1/0;
def main():
first()
if __name__ == "__main__":
main()
except SyntaxError as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
filename = exc_traceback.tb_frame.f_code.co_filename
lineno = exc_traceback.tb_lineno
line = linecache.getline(filename, lineno)
print("exception occurred at %s:%d: %s" % (filename, lineno, line))
print("**************************************************** ERROR ************************************************************************")
print("You have encountered an error !! no worries ,lets try figuring it out together")
print(" It looks like there is a syntax error in the statement:" , formatted_lines[2], " at line number " , exc_traceback.tb_lineno)
print("Make sure you look up the syntax , this may happen because ")
print(" Remember this is the error message always thrown " "'" ,e , "'")
同样,我也为其他例外而写...
现在我的问题是假设我想对所有程序使用这个脚本,或者比如假设try块在另一个文件中...然后我如何链接我的脚本和尝试阻止的程序..
或者如果我用不同的词语,那么我想要的是每当有一个try catch块时,catch块应该按照我的脚本而不是内置库来执行..
答案 0 :(得分:1)
如果要在调用此脚本的脚本中处理此异常,则需要引发异常。例如:
except SyntaxError as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
filename = exc_traceback.tb_frame.f_code.co_filename
lineno = exc_traceback.tb_lineno
line = linecache.getline(filename, lineno)
print("exception occurred at %s:%d: %s" % (filename, lineno, line))
print("**************************************************** ERROR ************************************************************************")
print("You have encountered an error !! no worries ,lets try figuring it out together")
print(" It looks like there is a syntax error in the statement:" , formatted_lines[2], " at line number " , exc_traceback.tb_lineno)
print("Make sure you look up the syntax , this may happen because ")
print(" Remember this is the error message always thrown " "'" ,e , "'")
#### Raise up the exception for handling in a calling script ####
raise e
然后在你的调用脚本中你只需要另外一个try-except块(假设你编写的'库文件'被称为mymodule.py并且两个文件都位于同一个工作目录中),就像这样
try:
import mymodule
mymodule.main()
except SyntaxError as e:
print("Exception found") # Optional: Add code to handle the exception
请记住,如果您无法处理此重新引发的异常,则会导致脚本失败并退出(打印异常消息和堆栈跟踪)。 这是一件好事。如果恢复方法未知或无法处理,遇到致命错误的脚本会以引起用户注意的方式失败编程。