Python try Keyword

❮ Python Keywords


Example

Try a block of code, and decide what to to if it raises an error:

try:
  x > 3
except:
  print("Something went wrong")
Try it Yourself »

Definition and Usage

The try keyword is used in try...except blocks. It defines a block of code test if it contains any errors.

You can define different blocks for different error types, and blocks to execute if nothing went wrong, see examples below.


More Examples

Example

Raise an error and stop the program when there is an error in the try block:

try:
  x > 3
except:
  Exception("Something went wrong")
Try it Yourself »

Related Pages

The except keyword.

The finally keyword.


❮ Python Keywords

Copyright 1999-2023 by Refsnes Data. All Rights Reserved.