Python Exception Handling

1) Basic Try/Except

Ask the user to input two numbers and perform division inside a try. Catch any exception and print:

An error occurred.

2) Catch ZeroDivisionError Only

Prompt for two integers and divide them. Handle only ZeroDivisionError with a message:

Error: You cannot divide by zero!

3) Catch ValueError

Ask the user to input an integer. Wrap in try, catch ValueError if input isn’t numeric.


4) Division with Multiple Except

Prompt for numbers and divide. Use separate except blocks for:

  • ValueError

  • ZeroDivisionError


5) Safe Input Loop

Keep asking for a valid integer until the user enters one (loop + exception).


6) Catch IndexError

Given list [10,20,30], ask for index and catch IndexError if input is out of bounds.


7) Catch KeyError

Given dict {"a":1, "b":2}, ask user for a key and catch KeyError if not found.


8) Use Else Block

In a try/except, add else: to print:

when division succeeds.


9) Use Finally Block

Open a file that may not exist (enter filename). Use finally: to always print:


10) Nested Try

Inside one try, convert input to int, then inside another try divide numbers. Handle errors separately.


11) Catch TypeError

Perform an invalid operation like 1 + "a" inside try and catch TypeError.


12) Raise Custom Error

Ask for age. If age < 0, raise ValueError("Age cannot be negative") inside a try.


13) Validate Range

Ask for a number 1–10. If out of range, raise and catch a ValueError.


14) Read File Safely

Ask for a filename and use try to open + read it; catch exceptions if it fails.


15) Continue on Error

Loop reading 5 integers from user. If one input causes ValueError, print message and continue the loop.


16) Log Exception Message

Catch an exception and print its error message using the exception object.

Example:


17) Validate Numeric CSV

Read a CSV file and convert a column to integers inside try/except to skip invalid rows.

(Dummy CSV like scores.csv with some non-numeric values.)


18) Cleanup with Finally

Open and read a file; in finally, close the file if it was successfully opened.


19) Safe Dictionary Access

Use try to access a dictionary value; in except print "Key not found".


20) Function with Exception Handling

Write a function safe_divide(a, b) that returns division result; handle errors with try inside the function and return "Error" on failure.


πŸ“Œ Concepts Practiced

Concept
Example

Basic try/except

Assignments 1,2,3

Multiple excepts

4,6,7

else block

8

finally block

9,18

Raising exceptions

12,13

Handling exceptions in loops

15

Error messages

16


πŸ’‘ Starter Template


canvil: 333f6c7d-6876-4f7e-b6ad-1bdb2233f5c1

Last updated