Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 4.4Error handling in Python

Errors occur in programs all the time. Some of these errors are undesirable and cause problems that should not be shown to the end user (client). This article covers supressing these errors as well as signalling errors in code.

Try...Except

The most common style in programming of supressing an exception is the Try...Except statement.

Just like in Java, PHP and many more C derived languages which follow the Try...Catch syntax, Python follows the Try...Except syntax. It has a very simple to understand structure:

Python
try:
  # If the code in here fails, it raises the except part of the Try...Except
  x = 5 / 0
except:
  # If an error occurs the except statement is activated and "Error found" is displayed
  print ("Error detected")
    

The comments in the sample explain what happens when an exception occurs, in essence if an error occurs within the try section, the except path is followed.

This except code block occurs on any error. This is very broad and does not give the programmer much information on what is wrong. That's where using exception types comes in:

Whilst the next sample does the same as the previous sample, it's purpose is to demonstrate how to use exception types:

Python
try:
  # If the code in here fails, it raises the except part of the Try...Except
  x = 5 / 0
except Exception:
# If an error occurs the except statement is activated and "Error found" is displayed print ("Error detected")

The highlighted line here denotes the line where the exception type should be used. For instance, a file exception would look like:

Python
try:
  # Try reading some file in here
except IOException:
  # If an error occurs the except statement is activated and "Error found" is displayed
  print ("File not found")
    

Raising errors

Errors can also be raised meaning that an error can be created. This can useful if the user inputs an incorrect value or an unexpected value. In Python, this is achieved with the raise keyword.

Python
name = input("Insert your name.")
try:
  # If the code in here fails, it raises the except part of the Try...Except
  if name == "Jamie":
    raise Exception("Invalid name")
except Exception:
  print ("Incorrect name")
    
  1. Modify the code inside a try block so that it does not generate an exception.
  2. Change the message displayed by an except block.
  3. Create a new try/except statement that catches an exception caused by dividing by zero.
  4. Modify the example that uses raise so that it triggers for a different value.

Rewrite the program so that it safely divides two numbers and displays an error message if an exception occurs.

Python
try:
    result = 10 / 0
    print(result)
except:
    print("An error occurred")
    

Modify the following program so that a different exception message is displayed.

Python
try:
    x = 5 / 0
except:
    print("Error detected")
    

Extension challenge: Ask the user to enter a number. If the user enters a negative number, use raise to generate an exception and display a suitable error message.

Feedback 👍
Comments are sent via email to me.