0

すべての実行時例外の処理 (catch ブロック) を除いたスクリプトを 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ブロックは組み込みライブラリではなくスクリプトに従って実行する必要があります..

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 に答える