9.11 (Optional) Stack Unwinding and Tracebacks

  • Each exception object stores information indicating the precise series of function calls that led to the exception
  • Helpful when debugging your code
In [1]:
def function1():
    function2()
    
In [2]:
def function2():
    raise Exception('An exception occurred')
  • Calling function1 results in the following traceback
In [3]:
function1()
------------------------------------------------------------------------
Exception                              Traceback (most recent call last)
<ipython-input-3-c0b3cafe2087> in <module>
----> 1 function1()

<ipython-input-1-a9f4faeeeb0c> in function1()
      1 def function1():
----> 2     function2()
      3 

<ipython-input-2-ce858d2ad885> in function2()
      1 def function2():
----> 2     raise Exception('An exception occurred')

Exception: An exception occurred

Traceback Details

  • Traceback shows the type of exception that occurred (Exception) followed by the complete function call stack that led to the raise point
  • The stack’s bottom function call is listed first

Stack Unwinding

  • When an exception is not caught in a given function, stack unwinding occurs
  • For an uncaught exception, IPython displays the traceback
    • In interactive mode, IPython awaits your next input
    • In a typical script, the script would terminate

Tip for Reading Tracebacks

  • When reading a traceback, start from the end of the traceback and read the error message first
  • Then, read upward through the traceback, looking for the first line that indicates code you wrote in your program
  • Typically, this is the location in your code that led to the exception

Exceptions in finally Suites

  • Raising an exception in a finally suite can lead to subtle, hard-to-find problems
  • A finally suite should always enclose in a try statement any code that may raise an exception

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.