Try-Except Block in Python

Level 384 keystrokes

This handles division by zero error gracefully, printing 'Result: 0'. Try-except catches and handles errors without crashing.

Python code

# try block contains code that might raise an error
1try:
# This will cause a ZeroDivisionError (can't divide by 0)
2 result = 10 / 0
# except catches the specific error type
# ZeroDivisionError occurs when dividing by zero
3except ZeroDivisionError:
# This runs instead of crashing the program
4 result = 0
# Print the result (0 because the error was handled)
5print(f"Result: {result}")

Output

Result: 0
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • :× 3
  • "× 2
  • =× 2
  • (× 1
  • )× 1
  • {× 1
  • }× 1
  • /× 1

More Python examples at level 3

← Python typing practice