Try except

Sometimes code throws an exception.

You can catch that exception using the try-except block.

The try-except statement starts with a block of code, and a response is specified in case an exception is thrown.

Note: In other programming languages this is often called try-catch.

Related Course:
Complete Python Bootcamp: Go from zero to hero in Python

Try-except example

Lets say we want to get numeric input from the keyboard and calculate the number squared.
The straight forward method would be:

This works as long as we give numeric input. If we would type “two”, the program crashes – an exception is thrown. That’s where try-catch comes in:

We can also be specific about the type of exception we want to catch:


Previous Post
Next Post

Leave a Reply