Python try Keyword

Example

Try a piece of code and determine what to do if an error is raised:

try:
  x > 3
except:
  print("Something went wrong")

Run Instance

Definition and Usage

The try keyword is used in the try...except block. It defines whether the code test block contains any errors.

You can define different blocks for different error types, as well as code blocks that are executed without any problems, see the following examples.

More Examples

Example

Throw an error and stop the program when an error occurs in the try block:

try:
  x > 3
except:
  raise Exception("Something went wrong")

Run Instance

Related Pages

except Keyword

finally Keyword