Python throw error

This guide is the ultimate resource for Python developers who want to design, implement, and maintain applications that can deal with errors properly.

Introduction

Software applications don’t run perfectly all the time. Despite intensive debugging and multiple testing levels, applications still fail. Bad data, broken network connectivity, corrupted databases, memory pressures, and unexpected user inputs can all prevent an application from performing normally. When such an event occurs, and the app is unable to continue its normal flow, this is known as an exception. And it’s your application’s job—and your job as a coder—to catch and handle these exceptions gracefully so that your app keeps working.

Install the Python SDK to identify and fix exceptions

What Are Python Exceptions?

Exceptions in Python applications can happen for many of the reasons stated above and more; and if they aren’t handled well, these exceptions can cause the program to crash, causing data loss, or worse, corrupted data. As a Python developer, you need to think about possible exception situations and include error handling in your code.

Fortunately, Python comes with a robust error handling framework. Using structured exception handling and a set of pre-defined exceptions, Python programs can determine the error type at run time and act accordingly. These can include actions like taking an alternate path, using default values, or prompting for correct input.

This article will show you how to raise exceptions in your Python code and how to address exceptions.

Difference Between Python Syntax Errors and Python Exceptions

Before diving in, it’s important to understand the two types of unwanted conditions in Python programming—syntax error and exception.

The syntax error exception occurs when the code does not conform to Python keywords, naming style, or programming structure. The interpreter sees the invalid syntax during its parsing phase and raises a SyntaxError exception. The program stops and fails at the point where the syntax error happened. That’s why syntax errors are exceptions that can’t be handled.

Here’s an example code block with a syntax error (note the absence of a colon after the “if” condition in parentheses):

a = 10
b = 20

if (a < b)
    print('a is less than b')

c = 30
print(c)

The interpreter picks up the error and points out the line number. Note how it doesn’t proceed after the syntax error:

File "test.py", line 4
    if (a < b)
             ^
SyntaxError: invalid syntax

Process finished with exit code 1

On the other hand, an exception happens when the code has no syntax error but encounters other error situations. These conditions can be addressed within the code—either in the current function or in the calling stack. In this sense, exceptions are not fatal. A Python program can continue to run if it gracefully handles the exception.

Here is an example of a Python code that doesn’t have any syntax errors. It’s trying to run an arithmetic operation on two string variables:

a = 'foo'
b = 'bar'
print(a % b)

The exception raised is TypeError:

Traceback (most recent call last):
  File "test.py", line 4, in 
    print(a % b)
TypeError: not all arguments converted during string formatting

Process finished with exit code 1

Python throws the TypeError exception when there are wrong data types. Similar to TypeError, there are several built-in exceptions like:

  1. ModuleNotFoundError
  2. ImportError
  3. MemoryError
  4. OSError
  5. SystemError
  6. … And so on

You can refer to the Python documentation for a full list of exceptions.

How to Throw an Exception in Python

Sometimes you want Python to throw a custom exception for error handling. You can do this by checking a condition and raising the exception, if the condition is True. The raised exception typically warns the user or the calling application.

You use the “raise” keyword to throw a Python exception manually. You can also add a message to describe the exception

Here is a simple example: Say you want the user to enter a date. The date has to be either today or in the future. If the user enters a past date, the program should raise an exception:

Python Throw Exception Example

from datetime import datetime

current_date = datetime.now()
print("Current date is: " + current_date.strftime('%Y-%m-%d'))

dateinput = input("Enter date in yyyy-mm-dd format: ")
# We are not checking for the date input format here
date_provided = datetime.strptime(dateinput, '%Y-%m-%d')
print("Date provided is: " + date_provided.strftime('%Y-%m-%d'))

if date_provided.date() < current_date.date():
    raise Exception("Date provided can't be in the past")

To test the code, we enter a date older than the current date. The “if” condition evaluates to true and raises the exception:

Current date is: 2021-01-24
Enter date in yyyy-mm-dd format: 2021-01-22
Date provided is: 2021-01-22
Traceback (most recent call last):
  File "test.py", line 13, in 
    raise Exception("Date provided can't be in the past")
Exception: Date provided can't be in the past

Process finished with exit code 1

Instead of raising a generic exception, we can specify a type for it, too:

if (date_provided.date() < current_date.date()):
    raise ValueError("Date provided can't be in the past")

With a similar input as before, Python will now throw this exception:

raise ValueError("Date provided can't be in the past")
ValueError: Date provided can't be in the past

Using AssertionError in Python Exception Throwing

Another way to raise an exception is to use assertion. With assertion, you assert a condition to be true before running a statement. If the condition evaluates to true, the statement runs, and the control continues to the next statement. However, if the condition evaluates to false, the program throws an AssertionError. The diagram below shows the logical flow:

Use AssertionError to raise and throw an exception in Python

Using AssertionError, we can rewrite the code snippet in the last section like this:

from datetime import datetime

current_date = datetime.now()
print("Current date is: " + current_date.strftime('%Y-%m-%d'))

dateinput = input("Enter date in yyyy-mm-dd format: ")
# We are not checking for the date input format here
date_provided = datetime.strptime(dateinput, '%Y-%m-%d')
print("Date provided is: " + date_provided.strftime('%Y-%m-%d'))

assert(date_provided.date() >= current_date.date()), "Date provided can't be in the past"

Note how we removed the “if” condition and are now asserting that the date provided is greater than or equal to the current date. When inputting an older date, the AssertionError displays:

Current date is: 2021-01-24
Enter date in yyyy-mm-dd format: 2021-01-23
Traceback (most recent call last):
Date provided is: 2021-01-23
  File "test.py", line 12, in 
    assert(date_provided.date() >= current_date.date()), "Date provided can't be in the past"
AssertionError: Date provided can't be in the past

Process finished with exit code 1

Catching Python Exceptions with Try-Except

Now that you understand how to throw exceptions in Python manually, it’s time to see how to handle those exceptions. Most modern programming languages use a construct called “try-catch” for exception handling. With Python, its basic form is “try-except”. The try-except block looks like this:

Python Try Catch Exception Example


...
try:
    <--program code-->
except:
    <--exception handling code-->
<--program code-->
...

Here, the program flow enters the “try” block. If there is an exception, the control jumps to the code in the “except” block. The error handling code you put in the “except” block depends on the type of error you think the code in the “try” block may encounter.

Here’s an example of Python’s “try-except” (often mistakenly referred to as “try-catch-exception”). Let’s say we want our code to run only if the Python version is 3. Using a simple assertion in the code looks like this:

import sys
assert (sys.version_info[0] == 3), "Python version must be 3"

If the of Python version is not 3, the error message looks like this:

Traceback (most recent call last):
  File "test.py", line 2, in 
    assert (sys.version_info[0] == 3), "Python version must be 3"
AssertionError: Python version must be 3

Process finished with exit code 1

Instead of letting the program fail with an unhandled exception and showing an ugly error message, we could use a try-except block for a graceful exit.

import sys
try:
    assert (sys.version_info[0] == 3), "Python version must be 3"
except Exception as e:
    print(e)
    rollbar.report_exc_info()

Now, the error message is much cleaner:

Python version must be 3

The “except” keyword in the construct also accepts the type of error you want to handle. To illustrate this, let’s go back to our date script from the last section. In that script, we assumed the user will enter a date in “YYYY-MM-DD” format. However, as a developer, you should cater to any type of erroneous data instead of depending on the user. For example, some exception scenarios can be:

  1. No date entered (blank)
  2. Text entered
  3. Number entered
  4. Time entered
  5. Special characters entered
  6. Different date format entered (such as “dd/mm/yyyy”)

To address all these conditions, we can rewrite the code block as shown below. This will catch any ValueError exception raised when meeting any of the above conditions:

from datetime import datetime

current_date = datetime.now()
print("Current date is: " + current_date.strftime('%Y-%m-%d'))

dateinput = input("Enter date in yyyy-mm-dd format: ")

try:
    date_provided = datetime.strptime(dateinput, '%Y-%m-%d')
except ValueError as e:
    print(e)
    rollbar.report_exc_info()
    exit()

print("Date provided is: " + date_provided.strftime('%Y-%m-%d'))
assert(date_provided.date() >= current_date.date()), "Date provided can't be in the past"

In this case, the program will exit gracefully if the date isn’t correctly formatted.

You can include multiple “except” blocks for the “try” block to trap different types of exceptions. Each “except” block will address a specific type of error:

...
try:
    <--program code-->
except <--Exception Type 1-->:
    <--exception handling code-->
except <--Exception Type 2-->:
    <--exception handling code-->
except <--Exception Type 3-->:
    <--exception handling code-->
...

Here’s a very simple example:

num0 = 10

try:
    num1 = input("Enter 1st number:")
    num2 = input("Enter 2nd number:")
    result = (int(num1) * int(num2))/(num0 * int(num2))
except ValueError as ve:
    print(ve)
    rollbar.report_exc_info()
    exit()
except ZeroDivisionError as zde:
    print(zde)
    rollbar.report_exc_info()
    exit()
except TypeError as te:
    print(te)
    rollbar.report_exc_info()
    exit()
except:
    print('Unexpected Error!')
    rollbar.report_exc_info()
    exit()

print(result)

We can test this program with different values:

Enter 1st number:1
Enter 2nd number:0
division by zero

Enter 1st number:
Enter 2nd number:6
invalid literal for int() with base 10: ''

Enter 1st number:12.99
Enter 2nd number:33
invalid literal for int() with base 10: '12.99'

Catching Python Exceptions with Try-Except-Else

The next element in the Python “try-except” construct is “else”:

Python Try Except Else Example

...
try:
    <--program code-->
except <--Exception Type 1-->:
    <--exception handling code-->
except <--Exception Type 2-->:
    <--exception handling code-->
except <--Exception Type 3-->:
    <--exception handling code-->
...
else:
    <--program code to run if "try" block doesn't encounter any error-->
...

The “else” block runs if there are no exceptions raised from the “try” block. Looking at the code structure above, you can see the “else” in Python exception handling works almost the same as an “if-else” construct

To show how “else” works, we can slightly modify the arithmetic script’s code from the last section. If you look at the script, you will see we calculated the variable value of “result” using an arithmetic expression. Instead of putting this in the “try” block, you can move it to an “else” block. That way, the exception blocks any error raised while converting the input values to integers. And if there are no exceptions, the “else” block will perform the actual calculation:

num0 = 10

try:
    num1 = int(input("Enter 1st number:"))
    num2 = int(input("Enter 2nd number:"))
except ValueError as ve:
    print(ve)
    rollbar.report_exc_info()
    exit()
except ZeroDivisionError as zde:
    print(zde)
    rollbar.report_exc_info()
    exit()
except TypeError as te:
    print(te)
    rollbar.report_exc_info()
    exit()
except:
    print('Unexpected Error!')
    rollbar.report_exc_info()
    exit()
else:
    result = (num1 * num2)/(num0 * num2)
    print(result)

Using simple integers as input values runs the “else” block code:

Enter 1st number:2
Enter 2nd number:3
0.2

And using erroneous data like empty values, decimal numbers, or strings cause the corresponding “except” block to run and skip the “else” block:

Enter 1st number:s
invalid literal for int() with base 10: 's'

Enter 1st number:20
Enter 2nd number:
invalid literal for int() with base 10: ''

Enter 1st number:5
Enter 2nd number:6.4
invalid literal for int() with base 10: '6.4'

However, there’s still a possibility of unhandled exceptions when the “else” block runs:

Enter 1st number:1
Enter 2nd number:0
Traceback (most recent call last):
  File "test.py", line 19, in 
    result = (num1 * num2)/(num0 * num2)
ZeroDivisionError: division by zero

As you can see, both inputs are integers (1 and 0), and the “try” block successfully converts them to integers. When the “else” block runs, we see the exception.

So how do you handle errors in the “else” block? You guessed that right—you can use another “try-except-else” block within the outer “else” block:

Enter 1st number:1
Enter 2nd number:0
division by zero

Catching Python Exceptions with Try-Except-Else-Finally

Finally, we have the last optional block in Python error handling. And it’s literally called “finally”:

Python Try Finally Example

...
try:
    <--program code-->
except <--Exception Type 1-->:
    <--exception handling code-->
except <--Exception Type 2-->:
    <--exception handling code-->
except <-->Exception Type 3-->>:
    <--exception handling code-->
...
else:
    <--program code to run if "try" block doesn't encounter any error-->
finally:
    <--program code that runs regardless of errors in the "try" or "else" block-->

The “finally” block runs whether or not the “try” block’s code raises an exception. If there’s an exception, the code in the corresponding “except” block will run, and then the code in the “finally” block will run. If there are no exceptions, the code in the “else” block will run (if there’s an “else” block), and then the code in the “finally” block will run.

Since the code in the “finally” block always runs, you want to keep your “clean up” codes here, such as:

  1. Writing status messages to log files
  2. Resetting counters, lists, arrays
  3. Closing open files
  4. Closing database connections
  5. Resetting object variables
  6. Disconnecting from network resources
  7. … And so on

Here’s an example of using “finally”:

try:
    f = open("testfile.txt", 'r')
except FileNotFoundError as fne:
    rollbar.report_exc_info()
    print(fne)
    print('Creating file...')
    f = open("testfile.txt", 'w')
    f.write('2')
else:
    data=f.readline(1)
    print(data)
finally:
    print('Closing file')
    f.close()

Here, the “try” block tries to open a file for reading. If the file doesn’t exist, the exception block shows a warning message, creates the file, and adds a static value of “2” to it. If the file exists, the “else” block reads the first line of its content and prints that out. Finally, the “finally” block closes the file. This happens whether or not the file initially existed.

What we have discussed so far can be summarized in the flowchart below:

Python exception handling logical flow

How Rollbar Can Help Log and Track Python Errors

Rollbar is a continuous code improvement platform for software development teams. It offers an automated way to capture Python errors and failed tests in real time from all application stack layers and across all environments. This allows creating a proactive and automated response to application errors. The diagram below shows how Rollbar works:

Rollbar automated testing model

Rollbar natively works with a wide array of programming languages and frameworks, including Python. Python developers can install pyrollbar, Rollbar’s SDK for Python, using a tool like pip, importing the Rollbar class in the code, and sending Python exceptions to Rollbar. The code snippet below shows how easy it is:

import rollbar
rollbar.init('POST_SERVER_ITEM_ACCESS_TOKEN', 'dev')

try:
    # some code
except TypeError:
    rollbar.report_message('There is a data type mismatch', 'fatal')
except:
    rollbar.report_exc_info()

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing errors easier than ever. Try it today.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Raising and Handling Python Exceptions

A Python program terminates as soon as it encounters an error. In Python, an error can be a syntax error or an exception. In this article, you will see what an exception is and how it differs from a syntax error. After that, you will learn about raising exceptions and making assertions. Then, you’ll finish with a demonstration of the try and except block.

An introduction to exceptions in Python

Exceptions versus Syntax Errors

Syntax errors occur when the parser detects an incorrect statement. Observe the following example:

>>> print( 0 / 0 ))
  File "<stdin>", line 1
    print( 0 / 0 ))
                  ^
SyntaxError: invalid syntax

The arrow indicates where the parser ran into the syntax error. In this example, there was one bracket too many. Remove it and run your code again:

>>> print( 0 / 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero

This time, you ran into an exception error. This type of error occurs whenever syntactically correct Python code results in an error. The last line of the message indicated what type of exception error you ran into.

Instead of showing the message exception error, Python details what type of exception error was encountered. In this case, it was a ZeroDivisionError. Python comes with various built-in exceptions as well as the possibility to create self-defined exceptions.

Raising an Exception

We can use raise to throw an exception if a condition occurs. The statement can be complemented with a custom exception.

Illustration of  raise statement usage

If you want to throw an error when a certain condition occurs using raise, you could go about it like this:

x = 10
if x > 5:
    raise Exception('x should not exceed 5. The value of x was: {}'.format(x))

When you run this code, the output will be the following:

Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10

The program comes to a halt and displays our exception to screen, offering clues about what went wrong.

The AssertionError Exception

Instead of waiting for a program to crash midway, you can also start by making an assertion in Python. We assert that a certain condition is met. If this condition turns out to be True, then that is excellent! The program can continue. If the condition turns out to be False, you can have the program throw an AssertionError exception.

Python assert statement

Have a look at the following example, where it is asserted that the code will be executed on a Linux system:

import sys
assert ('linux' in sys.platform), "This code runs on Linux only."

If you run this code on a Linux machine, the assertion passes. If you were to run this code on a Windows machine, the outcome of the assertion would be False and the result would be the following:

Traceback (most recent call last):
  File "<input>", line 2, in <module>
AssertionError: This code runs on Linux only.

In this example, throwing an AssertionError exception is the last thing that the program will do. The program will come to halt and will not continue. What if that is not what you want?

The try and except Block: Handling Exceptions

The try and except block in Python is used to catch and handle exceptions. Python executes code following the try statement as a “normal” part of the program. The code that follows the except statement is the program’s response to any exceptions in the preceding try clause.

Diagram showing try and except statements

As you saw earlier, when syntactically correct code runs into an error, Python will throw an exception error. This exception error will crash the program if it is unhandled. The except clause determines how your program responds to exceptions.

The following function can help you understand the try and except block:

def linux_interaction():
    assert ('linux' in sys.platform), "Function can only run on Linux systems."
    print('Doing something.')

The linux_interaction() can only run on a Linux system. The assert in this function will throw an AssertionError exception if you call it on an operating system other then Linux.

You can give the function a try using the following code:

try:
    linux_interaction()
except:
    pass

The way you handled the error here is by handing out a pass. If you were to run this code on a Windows machine, you would get the following output:

You got nothing. The good thing here is that the program did not crash. But it would be nice to see if some type of exception occurred whenever you ran your code. To this end, you can change the pass into something that would generate an informative message, like so:

try:
    linux_interaction()
except:
    print('Linux function was not executed')

Execute this code on a Windows machine:

Linux function was not executed

When an exception occurs in a program running this function, the program will continue as well as inform you about the fact that the function call was not successful.

What you did not get to see was the type of error that was thrown as a result of the function call. In order to see exactly what went wrong, you would need to catch the error that the function threw.

The following code is an example where you capture the AssertionError and output that message to screen:

try:
    linux_interaction()
except AssertionError as error:
    print(error)
    print('The linux_interaction() function was not executed')

Running this function on a Windows machine outputs the following:

Function can only run on Linux systems.
The linux_interaction() function was not executed

The first message is the AssertionError, informing you that the function can only be executed on a Linux machine. The second message tells you which function was not executed.

In the previous example, you called a function that you wrote yourself. When you executed the function, you caught the AssertionError exception and printed it to screen.

Here’s another example where you open a file and use a built-in exception:

try:
    with open('file.log') as file:
        read_data = file.read()
except:
    print('Could not open file.log')

If file.log does not exist, this block of code will output the following:

This is an informative message, and our program will still continue to run. In the Python docs, you can see that there are a lot of built-in exceptions that you can use here. One exception described on that page is the following:

Exception FileNotFoundError

Raised when a file or directory is requested but doesn’t exist. Corresponds to errno ENOENT.

To catch this type of exception and print it to screen, you could use the following code:

try:
    with open('file.log') as file:
        read_data = file.read()
except FileNotFoundError as fnf_error:
    print(fnf_error)

In this case, if file.log does not exist, the output will be the following:

[Errno 2] No such file or directory: 'file.log'

You can have more than one function call in your try clause and anticipate catching various exceptions. A thing to note here is that the code in the try clause will stop as soon as an exception is encountered.

Look at the following code. Here, you first call the linux_interaction() function and then try to open a file:

try:
    linux_interaction()
    with open('file.log') as file:
        read_data = file.read()
except FileNotFoundError as fnf_error:
    print(fnf_error)
except AssertionError as error:
    print(error)
    print('Linux linux_interaction() function was not executed')

If the file does not exist, running this code on a Windows machine will output the following:

Function can only run on Linux systems.
Linux linux_interaction() function was not executed

Inside the try clause, you ran into an exception immediately and did not get to the part where you attempt to open file.log. Now look at what happens when you run the code on a Linux machine:

[Errno 2] No such file or directory: 'file.log'

Here are the key takeaways:

  • A try clause is executed up until the point where the first exception is encountered.
  • Inside the except clause, or the exception handler, you determine how the program responds to the exception.
  • You can anticipate multiple exceptions and differentiate how the program should respond to them.
  • Avoid using bare except clauses.

The else Clause

In Python, using the else statement, you can instruct a program to execute a certain block of code only in the absence of exceptions.

Diagram of try, except, and else statements in Python

Look at the following example:

try:
    linux_interaction()
except AssertionError as error:
    print(error)
else:
    print('Executing the else clause.')

If you were to run this code on a Linux system, the output would be the following:

Doing something.
Executing the else clause.

Because the program did not run into any exceptions, the else clause was executed.

You can also try to run code inside the else clause and catch possible exceptions there as well:

try:
    linux_interaction()
except AssertionError as error:
    print(error)
else:
    try:
        with open('file.log') as file:
            read_data = file.read()
    except FileNotFoundError as fnf_error:
        print(fnf_error)

If you were to execute this code on a Linux machine, you would get the following result:

Doing something.
[Errno 2] No such file or directory: 'file.log'

From the output, you can see that the linux_interaction() function ran. Because no exceptions were encountered, an attempt to open file.log was made. That file did not exist, and instead of opening the file, you caught the FileNotFoundError exception.

Cleaning Up After Using finally

Imagine that you always had to implement some sort of action to clean up after executing your code. Python enables you to do so using the finally clause.

Diagram explaining try except else finally statements

Have a look at the following example:

try:
    linux_interaction()
except AssertionError as error:
    print(error)
else:
    try:
        with open('file.log') as file:
            read_data = file.read()
    except FileNotFoundError as fnf_error:
        print(fnf_error)
finally:
    print('Cleaning up, irrespective of any exceptions.')

In the previous code, everything in the finally clause will be executed. It does not matter if you encounter an exception somewhere in the try or else clauses. Running the previous code on a Windows machine would output the following:

Function can only run on Linux systems.
Cleaning up, irrespective of any exceptions.

Summing Up

After seeing the difference between syntax errors and exceptions, you learned about various ways to raise, catch, and handle exceptions in Python. In this article, you saw the following options:

  • raise allows you to throw an exception at any time.
  • assert enables you to verify if a certain condition is met and throw an exception if it isn’t.
  • In the try clause, all statements are executed until an exception is encountered.
  • except is used to catch and handle the exception(s) that are encountered in the try clause.
  • else lets you code sections that should run only when no exceptions are encountered in the try clause.
  • finally enables you to execute sections of code that should always run, with or without any previously encountered exceptions.

Hopefully, this article helped you understand the basic tools that Python has to offer when dealing with exceptions.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Raising and Handling Python Exceptions

In this article, you will learn error and exception handling in Python.

By the end of the article, you’ll know:

  • How to handle exceptions using the try, except, and finally statements
  • How to create a custom exception
  • How to raise an exceptions
  • How to use built-in exception effectively to build robust Python programs
Python Exceptions
Python Exceptions

Table of contents

  • What are Exceptions?
    • Why use Exception
  • What are Errors?
    • Syntax error
    • Logical errors (Exception)
  • Built-in Exceptions
  • The try and except Block to Handling Exceptions
    • Catching Specific Exceptions
    • Handle multiple exceptions with a single except clause
  • Using try with finally
  • Using try with else clause
  • Raising an Exceptions
  • Exception Chaining
  • Custom and User-defined Exceptions
    • Customizing Exception Classes
  • Exception Lifecycle
  • Warnings

What are Exceptions?

An exception is an event that occurs during the execution of programs that disrupt the normal flow of execution (e.g., KeyError Raised when a key is not found in a dictionary.) An exception is a Python object that represents an error..

In Python, an exception is an object derives from the BaseException class that contains information about an error event that occurred within a method. Exception object contains:

  • Error type (exception name)
  • The state of the program when the error occurred
  • An error message describes the error event.

Exception are useful to indicate different types of possible failure condition.

For example, bellow are the few standard exceptions

  • FileNotFoundException
  • ImportError
  • RuntimeError
  • NameError
  • TypeError

In Python, we can throw an exception in the try block and catch it in except block.

Why use Exception

  • Standardized error handling: Using built-in exceptions or creating a custom exception with a more precise name and description, you can adequately define the error event, which helps you debug the error event.
  • Cleaner code: Exceptions separate the error-handling code from regular code, which helps us to maintain large code easily.
  • Robust application: With the help of exceptions, we can develop a solid application, which can handle error event efficiently
  • Exceptions propagation: By default, the exception propagates the call stack if you don’t catch it. For example, if any error event occurred in a nested function, you do not have to explicitly catch-and-forward it; automatically, it gets forwarded to the calling function where you can handle it.
  • Different error types: Either you can use built-in exception or create your custom exception and group them by their generalized parent class, or Differentiate errors by their actual class

What are Errors?

On the other hand, An error is an action that is incorrect or inaccurate. For example, syntax error. Due to which the program fails to execute.

The errors can be broadly classified into two types:

  1. Syntax errors
  2. Logical errors

Syntax error

The syntax error occurs when we are not following the proper structure or syntax of the language. A syntax error is also known as a parsing error.

When Python parses the program and finds an incorrect statement it is known as a syntax error. When the parser found a syntax error it exits with an error message without running anything.

Common Python Syntax errors:

  • Incorrect indentation
  • Missing colon, comma, or brackets
  • Putting keywords in the wrong place.

Example

print("Welcome to PYnative")
    print("Learn Python with us..")

Output

print("Learn Python with us..")
    ^
IndentationError: unexpected indent

Logical errors (Exception)

Even if a statement or expression is syntactically correct, the error that occurs at the runtime is known as a Logical error or Exception. In other words, Errors detected during execution are called exceptions.

Common Python Logical errors:

  • Indenting a block to the wrong level
  • using the wrong variable name
  • making a mistake in a boolean expression

Example

a = 10
b = 20
print("Addition:", a + c)

Output

print("Addition:", a + c)
NameError: name 'c' is not defined

Built-in Exceptions

The below table shows different built-in exceptions.

Python automatically generates many exceptions and errors. Runtime exceptions, generally a result of programming errors, such as:

  • Reading a file that is not present
  • Trying to read data outside the available index of a list
  • Dividing an integer value by zero
Exception Description
AssertionError Raised when an assert statement fails.
AttributeError Raised when attribute assignment or reference fails.
EOFError Raised when the input() function hits the end-of-file condition.
FloatingPointError Raised when a floating-point operation fails.
GeneratorExit Raise when a generator’s close() method is called.
ImportError Raised when the imported module is not found.
IndexError Raised when the index of a sequence is out of range.
KeyError Raised when a key is not found in a dictionary.
KeyboardInterrupt Raised when the user hits the interrupt key (Ctrl+C or Delete)
MemoryError Raised when an operation runs out of memory.
NameError Raised when a variable is not found in the local or global scope.
OSError Raised when system operation causes system related error.
ReferenceError Raised when a weak reference proxy is used to access a garbage collected referent.
Python Built-in Exceptions

Example: The FilenotfoundError is raised when a file in not present on the disk

fp = open("test.txt", "r")
if fp:
    print("file is opened successfully")

Output:

FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'

The try and except Block to Handling Exceptions

When an exception occurs, Python stops the program execution and generates an exception message. It is highly recommended to handle exceptions. The doubtful code that may raise an exception is called risky code.

To handle exceptions we need to use try and except block. Define risky code that can raise an exception inside the try block and corresponding handling code inside the except block.

Syntax

try :
    # statements in try block
except :
    # executed when exception occured in try block
try-except block
try-except block

The try block is for risky code that can raise an exception and the except block to handle error raised in a try block. For example, if we divide any number by zero, try block will throw ZeroDivisionError, so we should handle that exception in the except block.

When we do not use try…except block in the program, the program terminates abnormally, or it will be nongraceful termination of the program.

Now let’s see the example when we do not use try…except block for handling exceptions.

Example:

a = 10
b = 0
c = a / b
print("a/b = %d" % c)

Output

Traceback (most recent call last):
  File "E:/demos/exception.py", line 3, in <module>
    c = a / b
ZeroDivisionError: division by zero

We can see in the above code when we are divided by 0; Python throws an exception as ZeroDivisionError and the program terminated abnormally.

We can handle the above exception using the try…except block. See the following code.

Example

try:
    a = 10
    b = 0
    c = a/b
    print("The answer of a divide by b:", c)
except:
    print("Can't divide with zero. Provide different number")

Output

Can't divide with zero. Provide different number

Catching Specific Exceptions

We can also catch a specific exception. In the above example, we did not mention any specific exception in the except block. Catch all the exceptions and handle every exception is not good programming practice.

It is good practice to specify an exact exception that the except clause should catch. For example, to catch an exception that occurs when the user enters a non-numerical value instead of a number, we can catch only the built-in ValueError exception that will handle such an event properly.

We can specify which exception except block should catch or handle. A try block can be followed by multiple numbers of except blocks to handle the different exceptions. But only one exception will be executed when an exception occurs.

Example

In this example, we will ask the user for the denominator value. If the user enters a number, the program will evaluate and produce the result.

If the user enters a non-numeric value then, the try block will throw a ValueError exception, and we can catch that using a first catch block ‘except ValueError’ by printing the message ‘Entered value is wrong’.

And suppose the user enters the denominator as zero. In that case, the try block will throw a ZeroDivisionError, and we can catch that using a second catch block by printing the message ‘Can’t divide by zero’.

try:
    a = int(input("Enter value of a:"))
    b = int(input("Enter value of b:"))
    c = a/b
    print("The answer of a divide by b:", c)
except ValueError:
    print("Entered value is wrong")
except ZeroDivisionError:
    print("Can't divide by zero")

Output 1:

Enter value of a:Ten
Entered value is wrong

Output 2:

Enter value of a:10
Enter value of b:0
Can't divide by zero

Output 3:

Enter value of a:10
Enter value of b:2
The answer of a divide by b: 5.0

Handle multiple exceptions with a single except clause

We can also handle multiple exceptions with a single except clause. For that, we can use an tuple of values to specify multiple exceptions in an except clause.

Example

Let’s see how to specifiy two exceptions in the single except clause.

try:
    a = int(input("Enter value of a:"))
    b = int(input("Enter value of b:"))
    c = a / b
    print("The answer of a divide by b:", c)
except(ValueError, ZeroDivisionError):
    print("Please enter a valid value")

Using try with finally

Python provides the finally block, which is used with the try block statement. The finally block is used to write a block of code that must execute, whether the try block raises an error or not.

Mainly, the finally block is used to release the external resource. This block provides a guarantee of execution.

try-except-finally block
try-except-finally block

Clean-up actions using finally

Sometimes we want to execute some action at any cost, even if an error occurred in a program. In Python, we can perform such actions using a finally statement with a try and except statement.

The block of code written in the finally block will always execute even there is an exception in the try and except block.

If an exception is not handled by except clause, then finally block executes first, then the exception is thrown. This process is known as clean-up action.

Syntax

try:    
    # block of code     
    # this may throw an exception    
finally:    
    # block of code    
    # this will always be executed 
    # after the try and any except block   

Example

try:
    a = int(input("Enter value of a:"))
    b = int(input("Enter value of b:"))
    c = a / b
    print("The answer of a divide by b:", c)

except ZeroDivisionError:
    print("Can't divide with zero")
finally:
    print("Inside a finally block")

Output 1:

Enter value of a:20
Enter value of b:5
The answer of a divide by b: 4.0
Inside a finally block

Output 2:

Enter value of a:20
Enter value of b:0
Can't divide with zero
Inside a finally block

In the above example, we can see we divide a number by 0 and get an error, and the program terminates normally. In this case, the finally block was also executed.

Using try with else clause

Sometimes we might want to run a specific block of code. In that case, we can use else block with the try-except block. The else block will be executed if and only if there are no exception is the try block. For these cases, we can use the optional else statement with the try statement.

Why to use else block with try?

Use else statemen with try block to check if try block executed without any exception or if you want to run a specific code only if an exception is not raised

try-else block

Syntax

try:    
    # block of code     
except Exception1:    
    # block of code     
else:    
    # this code executes when exceptions not occured    
  • try: The try block for risky code that can throw an exception.
  • except: The except block to handle error raised in a try block.
  • else: The else block is executed if there is no exception.

Example

try:
    a = int(input("Enter value of a:"))
    b = int(input("Enter value of b:"))
    c = a / b
    print("a/b = %d" % c)

except ZeroDivisionError:
    print("Can't divide by zero")
else:
    print("We are in else block ")

Output 1

Enter value of a: 20
Enter value of b:4
a/b = 5
We are in else block 

Output 2

Enter value of a: 20
Enter value of b:0
Can't divide by zero

Raising an Exceptions

In Python, the raise statement allows us to throw an exception. The single arguments in the raise statement show an exception to be raised. This can be either an exception object or an Exception class that is derived from the Exception class.

The raise statement is useful in situations where we need to raise an exception to the caller program. We can raise exceptions in cases such as wrong data received or any validation failure.

Follow the below steps to raise an exception:

  • Create an exception of the appropriate type. Use the existing built-in exceptions or create your won exception as per the requirement.
  • Pass the appropriate data while raising an exception.
  • Execute a raise statement, by providing the exception class.

The syntax to use the raise statement is given below.

raise Exception_class,<value>  

Example

In this example, we will throw an exception if interest rate is greater than 100.

def simple_interest(amount, year, rate):
    try:
        if rate > 100:
            raise ValueError(rate)
        interest = (amount * year * rate) / 100
        print('The Simple Interest is', interest)
        return interest
    except ValueError:
        print('interest rate is out of range', rate)

print('Case 1')
simple_interest(800, 6, 8)

print('Case 2')
simple_interest(800, 6, 800)

Output:

Case 1
The Simple Interest is 384.0

Case 2
interest rate is out of range 800

Exception Chaining

The exception chaining is available only in Python 3. The raise statements allow us as optional from statement, which enables chaining exceptions. So we can implement exception chaining in python3 by using raise…from clause to chain exception.

When exception raise, exception chaining happens automatically. The exception can be raised inside except or finally block section. We also disabled exception chaining by using from None idiom.

Example

try:
    a = int(input("Enter value of a:"))
    b = int(input("Enter value of b:"))
    c = a/b
    print("The answer of a divide by b:", c)
except ZeroDivisionError as e:
    raise ValueError("Division failed") from e

# Output: Enter value of a:10
# Enter value of b:0
# ValueError: Division failed

In the above example, we use exception chaining using raise...from clause and raise ValueError division failed.

Custom and User-defined Exceptions

Sometimes we have to define and raise exceptions explicitly to indicate that something goes wrong. Such a type of exception is called a user-defined exception or customized exception.

The user can define custom exceptions by creating a new class. This new exception class has to derive either directly or indirectly from the built-in class Exception. In Python, most of the built-in exceptions also derived from the Exception class.

class Error(Exception):
    """Base class for other exceptions"""
    pass

class ValueTooSmallError(Error):
    """Raised when the input value is small"""
    pass

class ValueTooLargeError(Error):
    """Raised when the input value is large"""
    pass

while(True):
    try:
        num = int(input("Enter any value in 10 to 50 range: "))
        if num < 10:
            raise ValueTooSmallError
        elif num > 50:
            raise ValueTooLargeError
        break
    except ValueTooSmallError:
            print("Value is below range..try again")

    except ValueTooLargeError:
            print("value out of range...try again")

print("Great! value in correct range.")

Output

Enter any value in 10 to 50 range: 5
Value is below range..try again

Enter any value in 10 to 50 range: 60
value out of range...try again

Enter any value in 10 to 50 range: 11
Great! value in correct range.

In the above example, we create two custom classes or user-defined classes with names, ValueTooSmallError and ValueTooLargeError.When the entered value is below the range, it will raise ValueTooSmallError and if the value is out of then, it will raise ValueTooLargeError.

Customizing Exception Classes

We can customize the classes by accepting arguments as per our requirements. Any custom exception class must be Extending from BaseException class or subclass of BaseException.

In the above example, we create a custom class that is inherited from the base class Exception. This class takes one argument age. When entered age is negative, it will raise NegativeAgeError.

class NegativeAgeError(Exception):

    def __init__(self, age, ):
        message = "Age should not be negative"
        self.age = age
        self.message = message

age = int(input("Enter age: "))
if age < 0:
    raise NegativeAgeError(age)
# Output:
# raise NegativeAgeError(age)
# __main__.NegativeAgeError: -9

Output:

Enter age: -28
 Traceback (most recent call last):
   File "E:/demos/exception.py", line 11, in 
     raise NegativeAgeError(age)
 main.NegativeAgeError: -28

Done

Exception Lifecycle

  • When an exception is raised, The runtime system attempts to find a handler for the exception by backtracking the ordered list of methods calls. This is known as the call stack.
  • If a handler is found (i.e., if except block is located), there are two cases in the except block; either exception is handled or possibly re-thrown.
  • If the handler is not found (the runtime backtracks to the method chain’s last calling method), the exception stack trace is printed to the standard error console, and the application stops its execution.

Example

def sum_of_list(numbers):
    return sum(numbers)

def average(sum, n):
    # ZeroDivisionError if list is empty
    return sum / n

def final_data(data):
    for item in data:
        print("Average:", average(sum_of_list(item), len(item)))

list1 = [10, 20, 30, 40, 50]
list2 = [100, 200, 300, 400, 500]
# empty list
list3 = []
lists = [list1, list2, list3]
final_data(lists)

Output

Average: 30.0
Traceback (most recent call last):
File "E:/demos/exceptions.py", line 17, in
final_data(lists)
File "E:/demos/exceptions.py", line 11, in final_data
print("Average:", average(sum_of_list(item), len(item)))
Average: 300.0
File "E:/demos/exceptions.py", line 6, in average
return sum / n
ZeroDivisionError: division by zero

The above stack trace shows the methods that are being called from main() until the method created an exception condition. It also shows line numbers.

Warnings

Several built-in exceptions represent warning categories. This categorization is helpful to be able to filter out groups of warnings.

The warning doesn’t stop the execution of a program it indicates the possible improvement

Below is the list of warning exception

Waring Class Meaning
Warning Base class for warning categories
UserWarning Base class for warnings generated by user code
DeprecationWarning Warnings about deprecated features
PendingDeprecationWarning Warnings about features that are obsolete and expected to be deprecated in the future, but are not deprecated at the moment.
SyntaxWarning Warnings about dubious syntax
RuntimeWarning Warnings about the dubious runtime behavior
FutureWarning Warnings about probable mistakes in module imports
ImportWarning Warnings about probable mistakes in module imports
UnicodeWarning Warnings related to Unicode data
BytesWarning Warnings related to bytes and bytearray.
ResourceWarning Warnings related to resource usage
Python Exception warnings

How to Handle Exceptions in Python: A Detailed Visual Introduction

Welcome! In this article, you will learn how to handle exceptions in Python.

In particular, we will cover:

  • Exceptions
  • The purpose of exception handling
  • The try clause
  • The except clause
  • The else clause
  • The finally clause
  • How to raise exceptions

Are you ready? Let’s begin! 😀

1️⃣ Intro to Exceptions

We will start with exceptions:

  • What are they?
  • Why are they relevant?
  • Why should you handle them?

According to the Python documentation:

Errors detected during execution are called exceptions and are not unconditionally fatal.

Exceptions are raised when the program encounters an error during its execution. They disrupt the normal flow of the program and usually end it abruptly. To avoid this, you can catch them and handle them appropriately.

You’ve probably seen them during your programming projects.

If you’ve ever tried to divide by zero in Python, you must have seen this error message:

>>> a = 5/0
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    a = 5/0
ZeroDivisionError: division by zero

If you tried to index a string with an invalid index, you definitely got this error message:

>>> a = "Hello, World"
>>> a[456]
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    a[456]
IndexError: string index out of range

These are examples of exceptions.

🔹 Common Exceptions

There are many different types of exceptions, and they are all raised in particular situations. Some of the exceptions that you will most likely see as you work on your projects are:

  • IndexError — raised when you try to index a list, tuple, or string beyond the permitted boundaries. For example:
>>> num = [1, 2, 6, 5]
>>> num[56546546]
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    num[56546546]
IndexError: list index out of range
  • KeyError — raised when you try to access the value of a key that doesn’t exist in a dictionary. For example:
>>> students = {"Nora": 15, "Gino": 30}
>>> students["Lisa"]
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    students["Lisa"]
KeyError: 'Lisa'
  • NameError — raised when a name that you are referencing in the code doesn’t exist. For example:
>>> a = b
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    a = b
NameError: name 'b' is not defined
  • TypeError — raised when an operation or function is applied to an object of an inappropriate type. For example:
>>> (5, 6, 7) * (1, 2, 3)
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    (5, 6, 7) * (1, 2, 3)
TypeError: can't multiply sequence by non-int of type 'tuple'
  • ZeroDivisionError — raised when you try to divide by zero.
>>> a = 5/0
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    a = 5/0
ZeroDivisionError: division by zero

💡 Tips: To learn more about other types of built-in exceptions, please refer to this article in the Python Documentation.

🔸 Anatomy of an Exception

I’m sure that you must have noticed a general pattern in these error messages. Let’s break down their general structure piece by piece:

image-8

First, we find this line (see below). A traceback is basically a list detailing the function calls that were made before the exception was raised.

The traceback helps you during the debugging process because you can analyze the sequence of function calls that resulted in the exception:

Traceback (most recent call last):

Then, we see this line (see below) with the path to the file and the line that raised the exception. In this case, the path was the Python shell <pyshell#0> since the example was executed directly in IDLE.

File "<pyshell#0>", line 1, in <module>
   a - 5/0

💡 Tip: If the line that raised the exception belongs to a function, <module>  is replaced by the name of the function.

Finally, we see a descriptive message detailing the type of exception and providing additional information to help us debug the code:

NameError: name 'a' is not defined

2️⃣ Exception Handling: Purpose & Context

You may ask: why would I want to handle exceptions? Why is this helpful for me? By handling exceptions, you can provide an alternative flow of execution to avoid crashing your program unexpectedly.

🔹 Example: User Input

Imagine what would happen if a user who is working with your program enters an invalid input. This would raise an exception because an invalid operation was performed during the process.

If your program doesn’t handle this correctly, it will crash suddenly and the user will have a very disappointing experience with your product.

But if you do handle the exception, you will be able to provide an alternative to improve the experience of the user.

Perhaps you could display a descriptive message asking the user to enter a valid input, or you could provide a default value for the input. Depending on the context, you can choose what to do when this happens, and this is the magic of error handling. It can save the day when unexpected things happen. ⭐️

🔸 What Happens Behind the Scenes?

Basically, when we handle an exception, we are telling the program what to do if the exception is raised. In that case, the «alternative» flow of execution will come to the rescue. If no exceptions are raised, the code will run as expected.

image-10

3️⃣ Time to Code: The try … except Statement

Now that you know what exceptions are and why you should we handle them, we will start diving into the built-in tools that the Python languages offers for this purpose.

First, we have the most basic statement: try … except.

Let’s illustrate this with a simple example. We have this small program that asks the user to enter the name of a student to display his/her age:

students = {"Nora": 15, "Gino": 30}

def print_student_age():
    name = input("Please enter the name of the student: ")
    print(students[name])

print_student_age()

Notice how we are not validating user input at the moment, so the user might enter invalid values (names that are not in the dictionary) and the consequences would be catastrophic because the program would crash if a KeyError is raised:

# User Input
Please enter the name of the student: "Daniel"

# Error Message
Traceback (most recent call last):
  File "<path>", line 15, in <module>
    print_student_age()
  File "<path>", line 13, in print_student_age
    print(students[name])
KeyError: '"Daniel"'

🔹 Syntax

We can handle this nicely using try … except. This is the basic syntax:

image-11

In our example, we would add the try … except statement within the function. Let’s break this down piece by piece:

students = {"Nora": 15, "Gino": 30}

def print_student_age():
    while True:
        try:
            name = input("Please enter the name of the student: ")
            print(students[name])
            break
        except:
            print("This name is not registered")
    

print_student_age()

If we «zoom in», we see the try … except statement:

try:
	name = input("Please enter the name of the student: ")
	print(students[name])
	break
except:
	print("This name is not registered")
  • When the function is called, the try clause will run. If no exceptions are raised, the program will run as expected.
  • But if an exception is raised in the try clause, the flow of execution will immediately jump to the except clause to handle the exception.

💡 Note: This code is contained within a while loop to continue asking for user input if the value is invalid. This is an example:

Please enter the name of the student: "Lulu"
This name is not registered
Please enter the name of the student: 

This is great, right? Now we can continue asking for user input if the value is invalid.

At the moment, we are handling all possible exceptions with the same except clause. But what if we only want to handle a specific type of exception? Let’s see how we could do this.

🔸 Catching Specific Exceptions

Since not all types of exceptions are handled in the same way, we can specify which exceptions we would like to handle with this syntax:

image-15

This is an example. We are handling the ZeroDivisionError exception in case the user enters zero as the denominator:

def divide_integers():
    while True:
        try:
            a = int(input("Please enter the numerator: "))
            b = int(input("Please enter the denominator: "))
            print(a / b)
        except ZeroDivisionError:
            print("Please enter a valid denominator.")


divide_integers()

This would be the result:

# First iteration
Please enter the numerator: 5
Please enter the denominator: 0
Please enter a valid denominator. 

# Second iteration
Please enter the numerator: 5
Please enter the denominator: 2
2.5

We are handling this correctly. But… if another type of exception is raised, the program will not handle it gracefully.

Here we have an example of a ValueError because one of the values is a float, not an int:

Please enter the numerator: 5
Please enter the denominator: 0.5
Traceback (most recent call last):
  File "<path>", line 53, in <module>
    divide_integers()
  File "<path>", line 47, in divide_integers
    b = int(input("Please enter the denominator: "))
ValueError: invalid literal for int() with base 10: '0.5'

We can customize how we handle different types of exceptions.

🔹 Multiple Except Clauses

To do this, we need to add multiple except clauses to handle different types of exceptions differently.

According to the Python Documentation:

A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed.

In this example, we have two except clauses. One of them handles ZeroDivisionError and the other one handles ValueError, the two types of exceptions that could be raised in this try block.

def divide_integers():
    while True:
        try:
            a = int(input("Please enter the numerator: "))
            b = int(input("Please enter the denominator: "))
            print(a / b)
        except ZeroDivisionError:
            print("Please enter a valid denominator.")
        except ValueError:
            print("Both values have to be integers.")


divide_integers() 

💡 Tip: You have to determine which types of exceptions might be raised in the try block to handle them appropriately.

🔸 Multiple Exceptions, One Except Clause

You can also choose to handle different types of exceptions with the same except clause.

According to the Python Documentation:

An except clause may name multiple exceptions as a parenthesized tuple.

This is an example where we catch two exceptions (ZeroDivisionError and ValueError) with the same except clause:

def divide_integers():
    while True:
        try:
            a = int(input("Please enter the numerator: "))
            b = int(input("Please enter the denominator: "))
            print(a / b)
        except (ZeroDivisionError, ValueError):
            print("Please enter valid integers.")

divide_integers()

The output would be the same for the two types of exceptions because they are handled by the same except clause:

Please enter the numerator: 5
Please enter the denominator: 0
Please enter valid integers.
Please enter the numerator: 0.5
Please enter valid integers.
Please enter the numerator: 

🔹 Handling Exceptions Raised by Functions Called in the try Clause

An interesting aspect of exception handling is that if an exception is raised in a function that was previously called in the try clause of another function and the function itself does not handle it, the caller will handle it if there is an appropriate except clause.

According to the Python Documentation:

Exception handlers don’t just handle exceptions if they occur immediately in the try clause, but also if they occur inside functions that are called (even indirectly) in the try clause.

Let’s see an example to illustrate this:

def f(i):
    try:
        g(i)
    except IndexError:
        print("Please enter a valid index")

def g(i):
    a = "Hello"
    return a[i]

f(50)

We have the f function and the g function. f calls g in the try clause. With the argument 50, g will raise an IndexError because the index 50 is not valid for the string a.

But g itself doesn’t handle the exception. Notice how there is no try … except statement in the g function. Since it doesn’t handle the exception, it «sends» it to f to see if it can handle it, as you can see in the diagram below:

image-16

Since f does know how to handle an IndexError, the situation is handled gracefully and this is the output:

Please enter a valid index

💡 Note: If f had not handled the exception, the program would have ended abruptly with the default error message for an IndexError.

🔸 Accessing Specific Details of Exceptions

Exceptions are objects in Python, so you can assign the exception that was raised to a variable. This way, you can print the default description of the exception and access its arguments.

According to the Python Documentation:

The except clause may specify a variable after the exception name. The variable is bound to an exception instance with the arguments stored in instance.args.

Here we have an example (see below) were we assign the instance of ZeroDivisionError to the variable e. Then, we can use this variable within the except clause to access the type of the exception, its message, and arguments.

def divide_integers():
    while True:
        try:
            a = int(input("Please enter the numerator: "))
            b = int(input("Please enter the denominator: "))
            print(a / b)
        # Here we assign the exception to the variable e
        except ZeroDivisionError as e:
            print(type(e))
            print(e)
            print(e.args)

divide_integers()

The corresponding output would be:

Please enter the numerator: 5
Please enter the denominator: 0

# Type
<class 'ZeroDivisionError'>

# Message
division by zero

# Args
('division by zero',)

💡 Tip: If you are familiar with special methods, according to the Python Documentation: «for convenience, the exception instance defines __str__() so the arguments can be printed directly without having to reference .args

4️⃣ Now Let’s Add: The «else» Clause

The else clause is optional, but it’s a great tool because it lets us execute code that should only run if no exceptions were raised in the try clause.

image-17

According to the Python Documentation:

The tryexcept statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception.

Here is an example of the use of the else clause:

def divide_integers():
    while True:
        try:
            a = int(input("Please enter the numerator: "))
            b = int(input("Please enter the denominator: "))
            result = a / b
        except (ZeroDivisionError, ValueError):
            print("Please enter valid integers. The denominator can't be zero")
        else:
            print(result)

divide_integers()

If no exception are raised, the result is printed:

Please enter the numerator: 5
Please enter the denominator: 5
1.0

But if an exception is raised, the result is not printed:

Please enter the numerator: 5
Please enter the denominator: 0
Please enter valid integers. The denominator can't be zero

💡 Tip: According to the Python Documentation:

The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the tryexcept statement.

5️⃣ The «finally» Clause

The finally clause is the last clause in this sequence. It is optional, but if you include it, it has to be the last clause in the sequence. The finally clause is always executed, even if an exception was raised in the try clause.  

image-19

According to the Python Documentation:

If a finally clause is present, the finally clause will execute as the last task before the try statement completes. The finally clause runs whether or not the try statement produces an exception.

The finally clause is usually used to perform «clean-up» actions that should always be completed. For example, if we are working with a file in the try clause, we will always need to close the file, even if an exception was raised when we were working with the data.

Here is an example of the finally clause:

def divide_integers():
    while True:
        try:
            a = int(input("Please enter the numerator: "))
            b = int(input("Please enter the denominator: "))
            result = a / b
        except (ZeroDivisionError, ValueError):
            print("Please enter valid integers. The denominator can't be zero")
        else:
            print(result)
        finally:
            print("Inside the finally clause")

divide_integers()

This is the output when no exceptions were raised:

Please enter the numerator: 5
Please enter the denominator: 5
1.0
Inside the finally clause

This is the output when an exception was raised:

Please enter the numerator: 5
Please enter the denominator: 0
Please enter valid integers. The denominator can't be zero
Inside the finally clause

Notice how the finally clause always runs.

❗️Important: remember that the else clause and the finally clause are optional, but if you decide to include both, the finally clause has to be the last clause in the sequence.

6️⃣ Raising Exceptions

Now that you know how to handle exceptions in Python, I would like to share with you this helpful tip: you can also choose when to raise exceptions in your code.

This can be helpful for certain scenarios. Let’s see how you can do this:

image-20

This line will raise a ValueError with a custom message.

Here we have an example (see below) of a function that prints the value of the items of a list or tuple, or the characters in a string. But you decided that you want the list, tuple, or string to be of length 5. You start the function with an if statement that checks if the length of the argument data is 5. If it isn’t, a ValueError exception is raised:

def print_five_items(data):
    
    if len(data) != 5:
        raise ValueError("The argument must have five elements")
    
    for item in data:
        print(item)

print_five_items([5, 2])

The output would be:

Traceback (most recent call last):
  File "<path>", line 122, in <module>
    print_five_items([5, 2])
  File "<path>", line 117, in print_five_items
    raise ValueError("The argument must have five elements")
ValueError: The argument must have five elements

Notice how the last line displays the descriptive message:

ValueError: The argument must have five elements

You can then choose how to handle the exception with a try … except statement. You could add an else clause and/or a finally clause. You can customize it to fit your needs.

🔹 Helpful Resources

  • Exceptions
  • Handling Exceptions
  • Defining Clean-up Actions

I hope you enjoyed reading my article and found it helpful. Now you have the necessary tools to handle exceptions in Python and you can use them to your advantage when you write Python code. ? Check out my online courses. You can follow me on Twitter.

⭐️ You may enjoy my other freeCodeCamp /news articles:

  • The @property Decorator in Python: Its Use Cases, Advantages, and Syntax
  • Data Structures 101: Graphs — A Visual Introduction for Beginners
  • Data Structures 101: Arrays — A Visual Introduction for Beginners


Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Понравилась статья? Поделить с друзьями:
  • Python syntax error non utf 8
  • Python syntax error meme
  • Python syntax error file stdin line 1
  • Python subprocess error code
  • Python solver error