2012-10-31 3 views
0

모든 런타임 예외에 대한 처리 (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 catch 블록이있을 때마다 내가 원하는 것은 catch 블록이 스크립트마다 실행되어야합니다. 내장 라이브러리 대신 ...

+0

코드를 볼 수 있습니까? –

+0

@shikhapanghal : 귀하의 질문을 편집하여 거기에 코드를 넣으십시오 – avasal

+0

질문을 수정했습니다 –

답변

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 

합니다 ('라이브러리 파일'당신이 쓴 가정은 mymodule.py라고하며 두 파일은 같은 작업 디렉토리에) 너무

처럼

이 다시 제기 된 예외를 처리하지 못하면 스크립트가 실패하고 종료됩니다 (예외 메시지 및 스택 추적 인쇄). 이것은 좋은 일입니다. 치명적인 오류가 발생하는 스크립트 은 복구 방법을 알 수 없거나 프로그래밍 방식으로 처리 할 수없는 경우 사용자의주의를 끄는 방식으로 실패합니다.

+0

UR 답장을 보내 주셔서 감사합니다. 아주 정교하지만 나는 어디에서 UR 예외를 발생시키는 요점을 얻을 수 있습니다. #### 호출 스크립트 ####에서 처리 예외를 발생시킵니다. dnt는이 목적을 얻습니다/ –

+0

만약 호출자는 호출 수신자에서 처리 할 수없는 오류가 있습니다. 예외는 호출 수신자에서 호출자로 전달되며 반대의 경우는 예외이므로 호출 수신자 스크립트는 예외가 발생했는지 전혀 알 수 없습니다. –

+0

ur 답장을 보내 주셔서 감사합니다. 아주 정교하지만 난 cdnt 어디에 요점을 얻을 수있는 예외를 제기 # # # 호출 스크립트에서 처리에 대한 예외를 제기 #### .. dnt이 목적을 얻으/ –

관련 문제