The try except statement can handle exceptions. Exceptions may happen when you run a program.

Exceptions are errors that happen during execution of the program. Python won’t tell you about errors like syntax errors (grammar faults), instead it will abruptly stop.

An abrupt exit is bad for both the end user and developer.

Instead of an emergency halt, you can use a try except statement to properly deal with the problem. An emergency halt will happen if you do not properly handle exceptions.

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


Lets take this scenario: _The program asks for numeric user input. Instead the user types characters in the input box. The program normally would crash. _

Try except

The try except statement prevents the program from crashing and properly deals with it.

x = input("Enter number: ")
x = x + 1
print("Invalid input")

Entering invalid input, makes the program continue normally:

try except


The try except statement can be extended with the finally keyword, this will be executed if no exception is thrown:

print("Valid input.")

The program continues execution if no exception has been thrown.

There are different kinds of exceptions: ZeroDivisionError, NameError, TypeError and so on. Sometimes modules define their own exceptions.


  1. Can try-except be used to catch invalid keyboard input?
  2. Can try-except catch the error if a file can’t be opened?
  3. When would you not use try-except?

Download answers