Skip to main content

Exception & Error Handling in Python

Errors and exceptions can lead to program failure or unexpected behavior, and Python comes with a robust set of tools to improve the stability of the code.
· 11 min read

Explore with AI

Errors and exceptions can lead to unexpected behavior or even stop a program from executing. Python provides various functions and mechanisms to handle these issues and improve the robustness of the code. In this tutorial, we will learn about various error types and built-in functions with examples. 

  • An error is a critical problem in code that typically cannot be recovered from at runtime, such as malformed syntax or wrong indentation.
  • An exception is a runtime event that disrupts normal program flow but can be caught and handled, allowing the program to continue.

While exceptions occur at runtime, some errors like SyntaxError and IndentationError are caught by the parser before the program even runs.

In simple words, the error is a critical issue that a normal application should not catch, while an exception is a condition that a program should catch. 

try except else finally process in Python

Let’s learn more about errors and exceptions by looking at various examples. To easily run these, you can create a DataLab workbook for free that has Python pre-installed and contains all code samples.

Errors in Python

Here is an example of a syntax error where a return outside the function means nothing. We should not handle errors in a program. Instead, we must create a function that returns the string. 

return "DataCamp"
Input In [1]
    return "DataCamp"
    ^
SyntaxError: 'return' outside function

We have created the function but with the wrong indentation. We should not handle indentation errors at runtime. We can do it manually or use code formatting tools.

def fun():
return "DataCamp"    
Input In [2]
    return "DataCamp"
    ^
IndentationError: expected an indented block

Exceptions in Python

We have encountered a ZeroDivisionError (Exception). We can handle it at runtime by using try and except blocks.

test = 1/0
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
Input In [4], in <cell line: 1>()
----> 1 test = 1/0

ZeroDivisionError: division by zero

NameError exceptions are quite common where a variable is not found. We can also handle the exception either by replacing the variable or printing the warning. 

y = test
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [5], in <cell line: 1>()
----> 1 y = test

NameError

Built-in Python Exceptions

Here is the list of default Python exceptions with descriptions:

  1. AssertionError: raised when the assert statement fails.

  2. EOFError: raised when the input() function meets the end-of-file condition.

  3. AttributeError: raised when the attribute assignment or reference fails.

  4. TabError: raised when the indentations consist of inconsistent tabs or spaces. 

  5. ImportError: raised when importing the module fails. 

  6. IndexError: occurs when the index of a sequence is out of range

  7. KeyboardInterrupt: raised when the user inputs interrupt keys (Ctrl + C or Delete).

  8. RuntimeError: occurs when an error does not fall into any category. 

  9. NameError: raised when a variable is not found in the local or global scope. 

  10. MemoryError: raised when programs run out of memory. 

  11. ValueError: occurs when the operation or function receives an argument with the right type but the wrong value. 

  12. ZeroDivisionError: raised when you divide a value or variable with zero. 

  13. SyntaxError: raised by the parser when the Python syntax is wrong. 

  14. IndentationError: occurs when there is a wrong indentation.

  15. SystemError: raised when the interpreter detects an internal error.

You can find a complete list of errors and exceptions in Python by reading the documentation. 

Learn about Python exceptions by taking our Object-Oriented Programming in Python course. It will teach you how to create classes and leverage inheritance and polymorphism to reuse and optimize code.

Exception Handling with try, except, else, and finally

After learning about errors and exceptions, we will learn to handle them by using try, except, else, and finally blocks. 

So, what do we mean by handling them? In normal circumstances, these errors will stop the code execution and display the error message. To create stable systems, we need to anticipate these errors and come up with alternative solutions or warning messages. 

In this section, we will learn what each block does and how we can use them to write robust code. 

The try and except statement 

The most simple way of handling exceptions in Python is by using the try and except block.  

  1. Run the code under the try statement.

  2. When an exception is raised, execute the code under the except statement. 

Instead of stopping at error or exception, our code will move on to alternative solutions. 

try except statement in Python

Simple example

In the first example, we will try to print the undefined x variable. In normal circumstances, it should throw the error and stop the execution, but with the try and except block, we can change the flow behavior. 

  • The program will run the code under the try statement. 
  • As we know, that x is not defined, so it will run the except statement and print the warning.
try:
   print(x)
except:
   print("An exception has occurred!")
An exception has occurred!

Multiple except statement example

In the second example, we will be using multiple except statements to handle multiple types of exceptions.

  •  If a ZeroDivisionError exception is raised, the program will print "You cannot divide a value with zero."
  • The rest of the exceptions will print “Something else went wrong.”

It allows us to write flexible code that can handle multiple exceptions at a time without breaking. 

Note: Avoid using a bare except: clause without specifying an exception type — it catches everything, including KeyboardInterrupt and SystemExit, which can make your program impossible to quit and hide unrelated bugs. Always catch the specific exception you expect, like except ZeroDivisionError:.

try:
   print(1/0)
        except ZeroDivisionError:
   print("You cannot divide a value with zero")
except:
   print("Something else went wrong")
You cannot divide a value with zero

Loading the file example

Now, let’s look at a more practical example. 

In the code below, we are reading the CSV file, and when it raises the FileNotFoundError exception, the code will print the error and an additional message about the data.csv file. 

Yes, we can print default error messages without breaking the execution. 

try:
   with open('data.csv') as file:
       read_data = file.read()
except FileNotFoundError as fnf_error:
   print(fnf_error)
   print("Explanation: We cannot load the 'data.csv' file")
[Errno 2] No such file or directory: 'data.csv'
Explanation: We cannot load the 'data.csv' file

The try with else clause

We have learned about try and except, and now we will be learning about the else statement.

When the try statement does not raise an exception, code enters into the else block. It is the remedy or a fallback option when you expect a part of your script will produce an exception. It is generally used in a brief setup or verification section where you don't want certain errors to hide. 

Note: In the try-except block, you can use the else after all the except statements. 

try with else clause in Python

Simple example

We are adding the else statement to the ZeroDivisionError example. As we can see, when there are no exceptions, the print function under the else statement is executed, displaying the result. 

try:
   result = 1/3
except ZeroDivisionError as err:
   print(err)
else:
   print(f"Your answer is {result}")
Your answer is 0.3333333333333333

IndexError with else example

Let’s learn more by creating a simple function and testing it for various scenarios. 

The find_nth_value() function has x (list) and n (index number) as arguments. We have created a try, except, and else block to handle the IndexError exception. 

x = [5,8,9,13]

def find_nth_value(x,n):
    try:
        result = x[n]
    except IndexError as err:
        print(err)
    else:
        print("Your answer is ", result)

The list x has four values, and we will test them for the 6th and 2nd indexes. 

# Testing
find_nth_value(x,6)
find_nth_value(x,2)