try
KeywordPython 2.0+Beginner
Starts a block of code that will be monitored for exceptions
Quick Info
- Documentation
- Official Docs
- Python Version
- 2.0+
Learn by Difficulty
Quick Example
python
try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!") try: number = int("hello") except ValueError as e: print(f"Invalid input: {e}") print("Program continues normally")
try/except prevents your program from crashing when errors occur. Always catch specific exceptions, not bare except.
Try in PlaygroundTags
languagesyntaxcoreerror-handlingexception
Related Items
except
Keyword
Catches and handles exceptions raised in a try block
finally
Keyword
Block that always executes after try/except, used for cleanup
else
Keyword
Catch-all branch when preceding if/elif conditions are all false
raise
Keyword
Throws an exception manually
with
Keyword
Wraps a block with a context manager for automatic setup/teardown