Handling Exceptions

Learn how to handle exceptions in a code so the application is not terminated.

Understanding the problem

To understand how we can handle exceptions, we must first understand what the origins of a problem might be. It’s only when we have understood this that we can insert measures to handle them correctly.

Let’s return to our function that divides two values. Let’s say this function takes two arguments, as it did in our previous example:

Press + to interact
function c(x, y)
result = x / y
end_function

We should assume that this function does something more than just print this single line. We can mark it out with some comments, as follows:

Press + to interact
function c(x, y)
# The function does some things here
result = x / y
# And even more things here
# It might even return a value
end_function

We know that because this function divides two values, we might get an exception if y is given a value of 0.

The first thing we should ask ourselves is if this is the best place to handle the problem. It could be, but most likely, it is not. This function is getting two values sent to it as arguments. Several parts of the application might use the function, so it has no way of knowing the source of the data that’s being sent to it.

What we can do, though, is check if ...