Software crash: exception handling in python

error, app crashed

Exception handling is a mechanism provided by programming languages to create robust software. A robust software handles errors and wrong inputs so the software doesn’t crash. In this article, I’ll show you how to do exception handling in python.

Why is important to create robust software that doesn’t crash?

All of us probably experienced a software crash. It is a bad experience must of us had when using the software.

Some of the crashes are very famous (infamous): The Windows operating system blue screen. Did you see it?

Did you lose all your work because the application you were using crashed?

One can lose hours and hours of work if the app we are using is not robust.

Let’s see how we can create robust applications, so our customers are happy with our product.

Exception Handling in Python

The mechanism we have available in programming languages to create robust applications is Exception Handling.

An exception occurs whenever there is an error in the application execution.

See some exception examples below when your software tries to:

  • read a file that does not exist.
  • create a file, but it does not have enough permission to carry out the operation.
  • apply an operator to invalid data. i.e. “John” / “Doe”
  • divide by 0.

Keyboard input example

Let’s imagine we need to enter a number using the keyboard. We have to take precautions and use exception handling, especially when users have to enter information.

In your program, a user has to enter a float number (i.e. employee salary). You can achieve that with the following line of code.

salary = float(input("Please enter the employee: "))

But if you execute that code, and enter anything different than a number, the result will be as follows:

exception in python, when you enter a string instead of a number

The execution of the program stops because of the exception.

How to avoid this issue?

Will be better to show a message to the user, telling him/her that the value must be a float number instead of something else?

The answer is yes, it will be better. Find bellow how to use exception handling in python to fix this issue.

while True:
    try:
        x = float(input("Enter the employee salary: "))
        break
    except ValueError:
        print("The salary has to be a number")

In the code above, we can see a block try-except. We read this type of block as follow: Try to enter a value from the keyboard and convert it to float. If everything is fine, execute break (this will take the execution out of the while loop). If the exception ValueError occurs, print a message in the console and keep the execution thread.

Next, the “while true” is executed, and because it is always true, python will execute what is inside of the loop, asking the user again for another number.

Let’s see what happen if we execute the code above and we make a mistake when entering the value.

exception handled result in python

As you can see in the result, now we have a robust application. Even you enter a wrong input it won’t crash. Nice isn’t it?

Divide by 0 example

See the code below.

number = int(input("Enter a number: "))

divisor = int(input("Enter a divisor: "))


print (number/divisor)

If we type 0 when we are asked for the divisor (it can happen by mistake), this will be the result.

division by zero python exception

As you can see, we get a division by zero exception and the program crash. We can solve this issue in a similar way to the previous example using exception handling in python.

number = int(input("Enter a number: "))

while True:
    divisor = int(input("Enter a divisor: "))
    try:
        result = number/divisor
        print(result)
        break
    except ZeroDivisionError:
        print("Division by 0 is undefined. Enter a divisor different than 0.")

See the result below.

division by zero exception handled result

Again, we created a more robust program.

What do you think it will happen if we enter a string as the divisor? Yes, you are right. The program will crash.

value error python exception.

But what happened? We already added exception handling.

Read carefully the error message. It shows that the exception that occurred is ValueError, and in our code, we only check for ZeroDivisionError.

In this case, we just have to add another possible exception: ValueError.

while True:
    try:
        number = int(input("Enter a number: "))
        divisor = int(input("Enter a divisor: "))
        result = number/divisor
        print(result)
        break
    except ZeroDivisionError:
        print("Division by 0 is undefined. Enter a divisor different than 0.")
    except ValueError:
        print("You have to enter two numbers, try again ...")

Now it will work as we expected. If you enter a string it will show you a message and ask again for the numbers. If the divisor is 0 it will show you an error message and will ask you again for the two numbers.

Notice that the code that can throw an exception, must be within the try block.  If the line that asks for the number is outside the try block, and we enter a string, the application will crash.

We can add as many except lines as we need. It depends on the exceptions you want to handle.

Exceptions class hierarchy

You can find all the predefined exceptions in python here.

There is one thing to understand from the hierarchy. Any time you capture a type of exception, you have to start using the types in the lower part of the hierarchy.

For instance, ArithmeticError inherits from Exception. You must capture ArithmeticError first.

If you capture Exception first (except Exception), then you won’t capture the arithmetic exception.

As you will see in another section of this post, you can create your own exception class. That new class must inherit from one of the classes that the system already have, usually Exception.

Finally, block

Sometimes, we want to execute some code without considering if an exception happened or not, or even if there is a keyboard interruption. Usually, Control + C, cancel the execution of a console application.

How can we execute a certain code always, before the program closes or after an exception that was captured, or even if the exception didn’t occur?

In that situation, we can use a finally block. See the example below.

while True:
    try:
        number = int(input("Enter a number: "))
        divisor = int(input("Enter a divisor: "))
        result = number/divisor
        print(result)
        break
    except ZeroDivisionError:
        print("Division by 0 is undefined. Enter a divisor different than 0.")
    except ValueError:
        print("You have to enter two numbers, try again ...")
    finally:
        print ("Do something that will always be executed.")

This type of block has special importance when we are using files. You will see why in the next article of this series.

Another use of exceptions

We often use Exceptions in another way. When we are implementing a class (or a group of classes) for someone else to use it, if we detect a violation, we throw an exception. So, the use of the class can catch the exception (with a try-except block) and handled it.

Let’s see the following example, let us create a class that will divide positive integer numbers. We are creating this class for other team members to use it.

class PositiveNumberException (Exception):
    def __init__(self, message):
        super(PositiveNumberException, self).__init__(message) #calling base parent constructor

def divide_positive_integers(number1, number2):
    if number1 < 1 or number2 < 1:
        raise PositiveNumberException("The numbers has to be positive")
    return number1/number2

In this case, we are creating a function that will divide two positive integer numbers. We can raise an exception if one of the numbers is not a positive integer number because the operation is not permitted in that case (as is not permitted to divide by 0).

We just have to create our own type of exception; I’m going to name it PositiveNumberException. It is recommended to use a meaningful name, like in the example. For that class to be considered an exception, has to inherit from the system class Exception (it is the base/parent class of all the exceptions).

Summary

We must create robust software using exception handling, so our users are happy with our product, we don’t make them lose time and our program do what is supposed to do.

There are different type of exceptions and they can occur under several circumstances.

While we are writing lines of code, we always have to think if our code can raise an exception. If it can happen, then we have to add exception handling to avoid a crash.

Users don’t like/use applications that crash.

One example of why we have to create robust applications. During the test for the Google Associate Android Developer certification, they tell you, if the app crashes you failed the test. It does not matter the rest; one crash and you fail.

This article is part of a series. See the order in which you suppose to read the articles in this series.

  1. OOP in python: classes and objects.
  2. OOP: Python lists.
  3. Inheritance and Polymorphism in Python with examples.
  4. How to solve problems using Inheritance and Polymorphism in Python.
  5. How to check if a user input is an integer in Python?

If you like the article, don’t forget to subscribe. It is free.

H@appy coding!

1 thought on “Software crash: exception handling in python”

  1. Greetings! I know this is kind of off topic but I was wondering if you knew
    where I could get a captcha plugin for my comment form? I’m using the
    same blog platform as yours and I’m having trouble finding one?
    Thanks a lot!

Comments are closed.