0

我已经在 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 块应该根据我的脚本而不是内置库执行。

4

1 回答 1

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

请记住,如果您未能处理此重新引发的异常,它将导致您的脚本失败并退出(打印异常消息和堆栈跟踪)。这是一件好事。如果恢复方法未知或无法以编程方式处理,则遇到致命错误的脚本应该以引起用户注意的方式失败。

于 2012-10-31T07:44:13.963 回答