Error Handling

try and except

Programs crash when something unexpected happens, like dividing by zero or converting bad text to a number. The try and except keywords let you catch these problems and keep your code running.


Sometimes Python code crashes. Dividing by zero, asking for an item that doesn't exist, converting bad text to a number — each one stops the program with an error.

Here is what an unhandled error looks like:

Python
Output

The line after the crash never ran. Python raised a ValueError and stopped. To keep your program running, you wrap risky code in a try block.

The basic syntax pairs try with except:

Python

Now the same code finishes cleanly:

Python
Output

What will be the output?

Python

A bare except catches everything, but that hides bugs. It's almost always better to name the exact exception you expect.

Here we only catch ValueError:

Python
Output

The conversion succeeded, so the except block was skipped. Common built-in exceptions you'll meet often are ValueError, TypeError, IndexError, KeyError, and ZeroDivisionError.


What will be the output?

Python

Once the except runs, the program keeps going:

Python
Output

What will be the output?

Python

If the exception you raise doesn't match the one you catch, Python still crashes. The except clause is picky about types.

A ValueError catch will not stop a ZeroDivisionError:

Python
Output

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python