Python · Exceptions

Complete Guide to Python Exceptions

An exception is an error that occurs while your program is running. If you do not handle exceptions, your program can crash. Python uses the try / except / else / finally system to handle errors safely.

1. Why Exceptions Are Important

Code without exception handling can crash on invalid data:

x = int("hello")   # ❌ ValueError
print("Program stopped")

Code with exception handling:

Now the program continues instead of stopping on error.

2. Basic try / except

Basic pattern. Enter a number and see how exceptions are handled.

Use this when you expect an operation might fail and you want to handle it gracefully instead of crashing.

3. Handling Specific Exceptions

It is better to catch specific errors instead of catching everything.

Common Exception Types

ExceptionWhen It Happens
ValueErrorWrong value, e.g. int("abc")
TypeErrorWrong data type, e.g. "5" + 3
ZeroDivisionErrorDivision by zero
IndexErrorInvalid list index
KeyErrorKey not found in dictionary
FileNotFoundErrorFile does not exist

4. Multiple except Blocks

You can handle different exceptions in different ways. Enter a number and see how each exception is handled.

5. The else Block

The else block runs only if no exception occurs in the try block.

6. The finally Block

The finally block always executes, whether an exception occurred or not. It is typically used for cleanup tasks (like closing files or connections). Here is an example, the code tries to open and read a file, this will work only if the code runs on local computer with a file named data.txt present.

7. Nested Exceptions

You can nest try / except blocks for more detailed handling. Enter a number and see how each exception is handled.

8. Raising Exceptions Manually with raise

You can trigger your own exceptions when something is wrong.

This stops the program and raises a ValueError with your custom message.

9. Creating Custom Exceptions

You can define custom exception types by inheriting from Exception. This makes your error handling more descriptive and domain-specific.

10. Using assert for Debugging

assert checks a condition and raises an AssertionError if the condition is false. It is useful for testing and debugging.

x = -5

assert x >= 0, "x must be positive"

11. Exception Hierarchy (Simplified)

BaseException
 └── Exception
      ├── ValueError
      ├── TypeError
      ├── IndexError
      ├── KeyError
      ├── ZeroDivisionError
      └── ...

If you catch Exception, you catch most normal runtime errors, but it is still better to catch specific types when possible.

12. Handling File Exceptions

Opening files can fail for many reasons (missing file, permissions, etc.), try it on personal computer to make it work, here it's just the example.

13. Real-World Example: Safe Calculator

A simple calculator that safely handles invalid input and division by zero.

This handles invalid input, division by zero, and any unexpected error.

14. Common Exception Handling Mistakes

MistakeWrongBetter
Catching everything blindly
try:
    ...
except:
    pass
try:
    ...
except ValueError:
    print("Invalid value")
Huge try block
try:
    # 50 lines of code
    ...
except Exception:
    print("Error")
try:
    risky_operation()
except SpecificError:
    handle_error()
Hiding errors completely
except:
    pass
except Exception as e:
    print("Error occurred:", e)

15. Best Practices & Summary

Good practices for using exceptions:

Exceptions help you build robust, stable, and user-friendly Python programs that handle errors instead of crashing unexpectedly.