...

/

Exceptions and the Call Stack

Exceptions and the Call Stack

Learn how exceptions are thrown in a call stack.

The call stack

Imagine that we have a program and that in it, we have a main function. This function is calling another function that calls another function, and so on. We’ll have something like the following:

Press + to interact
A function that calls a function that calls a function, and so on
A function that calls a function that calls a function, and so on

Keeping track of where we are in this chain of function calls is called the call stack, and that’s handled by the programming language when we run the program.

Example of an exception in a call stack

Now, imagine that we get an exception in the last function, called function c. This function will now exit immediately and return to where it was called—function b. This function will also exit as soon as the control gets handed back to it, and we’ll be returned to where we came from. This time, it’s function a. Again, this function will be terminated ...