Python Tutorial Python Advanced Python References Python Libraries

Python try Keyword



The Python try keyword is used in exception handling and it checks a block of statements for error. If any error occurs in the try block of statement, it will be handled by its except block of statement and the program will continue executing remaining part of code. Without try block, the program will stop immediately after an error and throw error message.

Syntax

try:
  statements
except:
  statements

Example:

In the example below, x is not defined anywhere in the program, which raises an error. As the error occurred in try block of statement, it will be handled by its except block of statement. Without try block, the program will stop immediately after an error and throw error message.

try:
  x = x + 1
  print(x)
except:
  print("An error occurred.")

print("But, it is handled by try-except blocks.")

The output of the above code will be:

An error occurred.
But, it is handled by try-except blocks.

❮ Python Keywords