简体   繁体   中英

stack trace and exception handling in python

I want to design a python program that handles exceptions in other programs , I also want this to access the stack trace in python . I am new t python development but am willing to learn but I do not have a direction on where to proceed . Could somebody please point me to a direction / resources that I could follow and maybe develop these skills , specifically what I should be learning to achieve my goal.

I want to develop this on python 2.7

Thank you for your responses.

EDIT : by handling exceptions , I just want to know what exception occured . Like in Java with try catch blocks where you can print out the stack trace and see if it is an arithmetic / array out of bounds error

Hi I was also thinking of something on this line something like

  try

 (Execute python program here)  // ie import this program 

 except : 1st exception
 except : 2nd exception
 .
 .
 etc

I know how to read from a file , but an unsure if this is correct for just executing a program written by somebody else?

Take a look at the traceback module. It formats and prints stack traces. You can use this is a top-level exception handler.

import sys
import traceback

try:
    do_something()
except:
    ex, val, tb = sys.exc_info()
    traceback.print_exception(ex, val, tb)

Python itself essentially does this on any uncaught excepton, then exits.

I am a little confused about your question; if you are only running other python code this will be automatic. You don't need to read any files, just import the python modules you want to use and call their functions. When these throw exceptions they will simply end up in your code and you can deal with them as you see fit, taking into account best practice regarding exception ahndling of course.

For a quick tutorial on python exceptions look here .

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