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

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")
    
Feedback 👍
Comments are sent via email to me.