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