Python Exception Handling Examples

Error handling is an important part of building robust programs. In Python, you can manage exceptions using try, except, finally, and more. These examples help beginners practice catching and managing errors gracefully.


1. Basic try-except block
python
try:
    print(10 / 0)
except ZeroDivisionError:
    print("You can't divide by zero!")

2. Handling multiple exceptions
python
try:
    x = int("abc")
except ValueError:
    print("Invalid integer conversion")
except TypeError:
    print("Type error occurred")

3. Using else with try-except
python
try:
    num = int("123")
except ValueError:
    print("Conversion failed")
else:
    print("Conversion successful:", num)

4. try-except-finally
python
try:
    result = 10 / 2
except ZeroDivisionError:
    print("Division error")
finally:
    print("This always runs")

5. Catching all exceptions
python
try:
    open("nonexistent.txt")
except Exception as e:
    print("An error occurred:", e)

6. Raise an exception manually
python
age = -1
if age < 0:
    raise ValueError("Age can't be negative")

7. Custom exception class
python
class MyError(Exception):
    pass

raise MyError("This is a custom error")

8. Handling IndexError
python
try:
    items = [1, 2]
    print(items[5])
except IndexError:
    print("Index out of range")

9. Handling FileNotFoundError
python
try:
    with open("missing.txt") as f:
        content = f.read()
except FileNotFoundError:
    print("File not found")

10. Nested try-except blocks
python
try:
    try:
        x = 1 / 0
    except ZeroDivisionError:
        print("Inner block: Division by zero")
except:
    print("Outer block")

11. Using pass in except
python
try:
    5 / 0
except ZeroDivisionError:
    pass

print("Program continues...")

12. Try-finally without except
python
try:
    print("Trying something")
finally:
    print("Cleanup code runs always")

13. ValueError handling
python
try:
    number = int("xyz")
except ValueError:
    print("That's not a valid number")

14. AttributeError example
python
try:
    x = 10
    x.append(5)
except AttributeError as e:
    print("Attribute error:", e)

15. TypeError handling
python
try:
    print("5" + 5)
except TypeError:
    print("Can't add string and integer")

16. KeyError in dictionary
python
try:
    d = {"a": 1}
    print(d["b"])
except KeyError:
    print("Key not found")

17. ImportError handling
python
try:
    import nonexistingmodule
except ImportError:
    print("Module not found")

18. Finally for resource cleanup
python
try:
    f = open("somefile.txt", "r")
except FileNotFoundError:
    print("File missing")
finally:
    print("Closing file (if opened)")

19. Using assertions
python
x = 0
assert x > 0, "x must be greater than 0"

20. Re-raising an exception
python
try:
    raise ValueError("Something went wrong")
except ValueError as e:
    print("Caught error:", e)
    raise

21. Validate user input
python
try:
    age = int(input("Enter your age: "))
except ValueError:
    print("Please enter a valid number")

22. Read a configuration file
python
try:
    with open("config.json", "r") as file:
        config = file.read()
except FileNotFoundError:
    print("Configuration file not found. Using defaults.")

23. API request with error handling
python
import requests

try:
    response = requests.get("https://api.example.com/data")
    data = response.json()
except requests.exceptions.RequestException as e:
    print("Request failed:", e)

24. Division with zero check
python
try:
    num = 10
    denom = 0
    result = num / denom
except ZeroDivisionError:
    print("Cannot divide by zero")

25. File upload size limit
python
def upload_file(size_mb):
    if size_mb > 100:
        raise OverflowError("File size exceeds 100MB limit")

try:
    upload_file(120)
except OverflowError as e:
    print("Upload failed:", e)

26. Dictionary key lookup
python
products = {"apple": 10, "banana": 5}

try:
    print("Price:", products["orange"])
except KeyError:
    print("Product not found")

27. Custom exception example
python
class NegativeNumberError(Exception):
    pass

number = -5
try:
    if number < 0:
        raise NegativeNumberError("Negative number not allowed")
except NegativeNumberError as e:
    print("Error:", e)

28. Logging an exception
python
import logging

logging.basicConfig(filename="app.log", level=logging.ERROR)

try:
    result = 5 / 0
except ZeroDivisionError as e:
    logging.error("Division error occurred", exc_info=True)


What’s Next?

Now that you know how to handle errors, it's time to learn about classes and objects. These are important concepts in Python that will help you organize and manage your code better. In the next section, we’ll go over examples of how to use classes and objects in Python.