In Python, errors (also called exceptions) can crash your program if not handled properly.
The try and except block helps you catch and handle those errors, allowing your code to run safely even when something goes wrong.
try: # Code that may raise an error except: # Code that runs if an error occurs
try: result = 10 / 0 except: print("Oops! You cannot divide by zero.") #Output - Oops! You cannot divide by zero.
try: num = int(input("Enter a number: ")) print(100 / num) except ZeroDivisionError: print("Cannot divide by zero.") except ValueError: print("Please enter a valid number.")
try: x = int(input("Enter a number: ")) print("You entered:", x) except ValueError: print("That's not a number!") else: print("No exceptions occurred!") finally: print("This block always runs.")
try
except
else
finally
ZeroDivisionError
ValueError
TypeError
FileNotFoundError
IndexError
KeyError