Inspecting Behavior

We may also wish to inspect the behavior of our program that could lead to a particular error. Specifically, we may need to know what set of function calls and classes lead to the error itself. In that case, we’ll need a way to see what code was executed before the bug was reached.

Stack Trace

One of the most useful ways to inspect the behavior of our application is to look at the call stack or stack trace of the program when it reaches an exception. The call stack will list all of the functions currently being executed, even including the individual line numbers of the currently executed piece of code.

For example, consider this code:

public class Test {
    public void functionA() throws Exception{
    public void functionB() throws Exception{
    public void functionC() throws Exception{
        throw new Exception("Test Exception");
    public static void main(String[] args) throws Exception{
        Test test = new Test();
class Test:
    def function_a(self) -> None:

    def function_b(self) -> None:

    def function_c(self) -> None:
        raise Exception("Test Exception")

This code includes a chain of three functions, and the innermost function will throw an exception. When we run this code, we’ll get the following error messages:

Exception in thread "main" java.lang.Exception: Test Exception
        at Test.functionC(
        at Test.functionB(
        at Test.functionA(
        at Test.main(
Traceback (most recent call last):
  File "", line 11, in <module>
  File "", line 3, in function_a
  File "", line 6, in function_b
  File "", line 9, in function_c
    raise Exception("Test Exception")
Exception: Test Exception

As we can see, both Java and Python will automatically print a stack trace of the exact functions and lines of code that we executed when we were reaching the error. Recall that this relates to the call stack in memory that is created while this program is executed:

Call Stack Call Stack

As we can see, Java will print the innermost call at the top of the call stack, whereas Python will invert the order and put the innermost call at the end. So, you’ll have to read carefully to make sure you are interpreting the call stack correctly.

What if we want to get a call stack without crashing our program? Both Java and Python support a method for this:


In both instances, we just need to import the appropriate library, and we have a method for examining the complex behaviors of our programs at our fingertips. Of course, as we’ll see in a bit, both debuggers and loggers can be used in conjunction with these methods to get even more information from our program.