Python Tutorials · Python Try...Except

Python Try...Except

Learn all about Python Try...Except in this comprehensive tutorial.

5 min read intermediate
  • The try block lets you test a block of code for errors.
  • When an error occurs, or exception as we call it, Python will normally stop and generate an error message.
  • You can define as many exception blocks as you want, e.
  • You can use the else keyword to define a block of code to be executed if no errors were raised:
  • The finally block, if specified, will be executed regardless if the try block raises an error or not.
  • As a Python developer you can choose to throw an exception if a condition occurs.

Introduction

The try block lets you test a block of code for errors.

The except block lets you handle the error.

The else block lets you execute code when there is no error.

The finally block lets you execute code, regardless of the result of the try- and except blocks.

Exception Handling

When an error occurs, or exception as we call it, Python will normally stop and generate an error message.

These exceptions can be handled using the try statement:

python

Since the try block raises an error, the except block will be executed.

Without the try block, the program will crash and raise an error:

python

Many Exceptions

You can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a special kind of error:

python

See more Error types in our Python Built-in Exceptions Reference.

Else

You can use the else keyword to define a block of code to be executed if no errors were raised:

python

Finally

The finally block, if specified, will be executed regardless if the try block raises an error or not.

python

This can be useful to close objects and clean up resources:

python

The program can continue, without leaving the file object open.

Raise an exception

As a Python developer you can choose to throw an exception if a condition occurs.

To throw (or raise) an exception, use the raise keyword.

python

The raise keyword is used to raise an exception.

You can define what kind of error to raise, and the text to print to the user.

python

Module quiz

2 questions
1

Which of the following is true about Python Try...Except?

2

What is the most common pitfall when working with Python Try...Except?

Answer all questions to submit.