我已经在 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 块的程序..
或者,如果我用不同的话来说,那么我想要的是每当有一个 try catch 块时,catch 块应该根据我的脚本而不是内置库执行。