Python try and except – Handling Errors Gracefully

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.



Why Use try and except?



Basic Syntax

try:
    # Code that may raise an error
except:
    # Code that runs if an error occurs


Example 1: Handling Division by Zero

try:
    result = 10 / 0
except:
    print("Oops! You cannot divide by zero.")

#Output - 
Oops! You cannot divide by zero.


Example 2: Catching Specific Exceptions

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.")


Example 3: Using else and finally

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.")


Keyword Meaning
try Code you want to test (may cause error)
except Code that runs if an error occurs
else (Optional) Code that runs if no error occurs
finally (Optional) Code that always runs, error or not (e.g., cleanup)


Common Built-in Exceptions


Exception Name Triggered When...
ZeroDivisionError You divide a number by zero
ValueError Invalid value (e.g., converting text to int)
TypeError Operation on incompatible data types
FileNotFoundError File doesn’t exist
IndexError List index out of range
KeyError Dictionary key not found


Summary




Practice Python Code Here: