Exceptions may occur during the execution of your program. If not handled correctly, exceptions can result in program termination. Imagine that your program asks the user for their year of birth and they input a letter instead. If you didn’t anticipate this possibility beforehand, the program will crash. This results in frustration for both user and programmer. 

In this article, we’ll explain Python exceptions, including how to handle them using Python’s integrated features and how to create your own. 

What Is an Exception in Python?

As a Python developer, you’ll inevitably run into exceptions. An exception is the result of an unpredicted event that occurs while your program is running, and prevents the program from doing what it should. As a result, the program throws an exception code.

An exception is different from an error. Errors can cause your program to crash or produce false results. They’re the result of a programming error, and the developer must correct them. An error can be syntactical or logical.

Syntax and Logical Errors

A syntax error causes the program to terminate because the interpreter cannot interpret it. This program crashes instantly because an apostrophe is missing. The console will display the following error:

print ('This is a syntax error)                                  ^SyntaxError: EOL while scanning string literal

Your only solution is to fix the error by adding the missing apostrophe just before the closing parenthesis.

Logical errors, on the other hand, do not necessarily lead to the program crashing, but can still be disastrous as they may go unnoticed. In the following example, we’ve got a program that tries to divide one number by another.

totalValue = (number1 * number2)

# Print the value 5
print("The result of the division is: ",totalValue)

But the operator is a multiplication symbol (*). The output is as follows:

The result of the division is:  20

The program did not crash, but the result is different than what we intended.

Example of an Exception

Let’s consider another program that’s meant to perform a division operation:

# Declare two variablesdividend = 10divisor = int(input("Enter the divisor: "))
# Perform a divisionquotient = (dividend / divisor)
# Print the quotientprint("The result of the division is: ",quotient)

At first glance, there’s nothing wrong with this program. The user simply inputs a value for the divisor, and the program does its job.

But if the user types in 0, then the program throws an exception because division by 0 is mathematically undefined:

Enter the divisor: 0Traceback (most recent call last):  File "main.py", line 7, in <module>    quotient = (dividend / divisor)ZeroDivisionError: division by zero

For your program to continue executing, you’ll need to handle the exception called ZeroDivisionError.

Let’s learn more about how a programmer can work with exceptions in Python.

Base Exceptions in Python

To handle exceptions, Python provides dedicated classes, all derived from a class called BaseExceptions. When an exception occurs, such as in our previous example, the compiler throws a built-in exception that derives from the BaseExceptions class.

You can use built-in exceptions within your code to prevent unwanted events from causing your program to stop working. Here are three common built-in exceptions:

AttributeError

An AttributeError will occur if the program tries to access an attribute that the object does not own. Here’s an example where an object OpelCorsa tries to access two attributes of its class:

class Car:
  def __init__(self,carType,weight):      self.carType=carType      self.weight=weight
OpelCorsa=Car("SuperMini",1300)
print(OpelCorsa.carType)print(OpelCorsa.length) 

The first print statement will work fine, since the attribute carType for OpelCorsa exists. But the second print statement will throw an AttributeError exception:

SuperMiniTraceback (most recent call last):  File "main.py", line 10, in <module>    print(OpelCorsa.length)AttributeError: 'Car' object has no attribute 'length'

That is because the attribute length does not exist. As we’ll see later, handling this exception will prevent the program from crashing.

ValueError

When a function receives an argument of the correct type but with an incorrect value, Python throws a ValueError. If a program asks the user their age:

# Input ageyourAge = int(input("Enter your age here: "))
# Print the ageprint(yourAge)

Below, our users replies with the word “twenty” rather than the number “20”:

Enter your age here: twentyTraceback (most recent call last):  File "main.py", line 2, in <module>    yourAge = int(input("Enter your age here: "))ValueError: invalid literal for int() with base 10: 'twenty'

Again, the program exits with a few lines mentioning that something has gone wrong.

TypeError

If you were to perform an action on an invalid/unsupported object type, the program would throw a TypeError . Now, let’s say you want to add the value of an int to a string

number1 = 3number2 = "3"
sumNumbers = number1 + number2

You would get the following result:

Traceback (most recent call last):  File "main.py", line 4, in <module>    sumNumbers = number1 + number2TypeError: unsupported operand type(s) for +: 'int' and 'str'


Your program has stopped executing because it is unable to add an int to a string.

How To Handle Exceptions in Python

Python provides exception handlers to handle exceptions to keep programs running smoothly rather than crashing. There are four of them: try, except, else, and finally. Here’s how they work in a pseudocode situation:

try:

       # code execution

except raises a built-in exception:

       # execute this code if an exception occurs

else:

       # if no exceptions was raised, execute this code

finally:

      # code that runs regardless of whether the exception has occurred 

Note: There can be multiple “except” statements, allowing you to catch multiple exceptions. 

Going back to our first example, here’s how we could handle a ZeroDivision exception in Python:

dividend = 10divisor = int(input("Enter the divisor: "))
try:    # Try to perform a division    quotient = (dividend / divisor)   except ZeroDivisionError:    # Print a message informing the user the input was incorrect    print("I'm sorry, division by zero is not possible in Python")   else:    # If the input is accepted, print the result    print ("The result of the division is ", quotient)   finally:    # A message that appears regardless of the input    print ("Thank you for using the division program")

By including the exception handlers, the program never terminates abruptly. This is so even if the user were to enter 0 as an input.

Enter the divisor: 0I'm sorry, division by zero is not possible in PythonThank you for using the division program

How To Raise Custom Exceptions in Python

Python’s extensive list of built-in exceptions is convenient for the programmer, as you can pick and use an existing exception type that’s closest to your needs. But what if you needed to handle an exception that doesn’t exist in the list of base exceptions? Fortunately, Python lets you create your own exceptions and handle them as if they were native. Here’s how to implement your own exceptions:

# define a custom exception based on the Exception classclass BelowSixteen(Exception):    pass...

First, create the exception based on the exception class. This is done by creating a class, giving it the Exception parameter.

...# we test if the user is at least 16try:    in_num = int(input("How old are you?:"))    if in_num < 16:        raise BelowSixteen...

The self-explanatory raise keyword is used to raise the exception. The code block below contains the code to execute if the exception is raised:

...except BelowSixteen:    print("I'm sorry, you are not eligible for a car driver's license")...

You can then use the except keyword the same way you’d use it with any built-in exception:

...else:    print("Congrats, you are eligible for a car driver’s license")   finally:    print("Goodbye!")

If the user entered an age below 16, they would get the following output:

How old are you?:3I'm sorry, you are not eligible for a car driver's licenceGoodbye!

The execution of the program executes with no issue, and you can always reuse your custom exceptions later in the program.

Learn Python Online

Exception handling ensures that your programs run smoothly and that your users have a great experience. Python provides exception handlers to help you catch exceptions and react accordingly. With the help of the built-in base exceptions, you can take care of the most common issues. If you need, you can create your own custom exceptions too.

Python is a powerful language with a wide range of applications, from machine learning to data science and much more. To start your exciting Python journey, enroll in our Introduction to Programming Nanodegree course today!

Complete Code Example

The custom exception

# define a custom exception based on the Exception classclass BelowSixteen(Exception):    pass
# we test if the user is at least 16try:    in_num = int(input("How old are you?:"))    if in_num < 16:        raise BelowSixteen       except BelowSixteen:    print("I'm sorry, you are not eligible for a car driver's license")
else:    print("Congrats, you are eligible for a car driver's license")   finally:    print("Goodbye!")