【发布时间】:2012-10-31 07:25:57
【问题描述】:
我已经在 python 中编写了一个脚本,其中包含所有运行时异常的除处理(捕获块)。如果我将 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 块应该按照我的脚本而不是内置库执行..
【问题讨论】:
-
@shikhapanghal:编辑您的问题并将代码放在那里
-
您的意思是您正在使用一些包含异常处理代码的库,但您想绕过该处理并在您的顶级异常处理程序中接收所有异常?