简体   繁体   中英

Library File for exception handling in python

I have written a script in python which has except handling(catch block) for all the runtime exceptions.If im putting the try block inside the same file as script then its printing the exception but my need is if the try block is in a different file then whats the procedure that it will use the catch blocks written in the script.

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 , "'")

Similarly i have written for other exceptions...

Now my question is suppose i want to use this script for all the programs or like suppose the try block in in a different file ...then how i can link my script and the program which has try block..

or if i put it in different words then what i want is whenever there is an try catch block then the catch block should executed as per my script instead of the built in library..

If you want to handle this exception in a script that calls this one you need to raise up the exception. For example:

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

Then in your calling script you just put another try-except block (assuming the 'library file' you wrote is called mymodule.py and both files reside in the same working directory) like so

try:
   import mymodule
   mymodule.main()
except SyntaxError as e:
   print("Exception found") # Optional: Add code to handle the exception

Keep in mind that if you fail to handle this re-raised exception it will cause your script to fail and exit (printing the exception message and stack trace). This is a good thing. A script which encounters a fatal error should fail in a way that gets the attention to the user if the method of recovery is unknown or cannot be handled programmatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM