Python Exception Handling
Welcome to Python Exception Handling at Ugenz Academy!
Errors can occur while a program is running. For example, a user might enter text instead of a number, a file might be missing, or a calculation might attempt to divide by zero.
Exception handling allows you to manage these situations gracefully instead of letting your program terminate unexpectedly.
What You Will Learn
- Exceptions: Understand runtime problems such as
ValueErrorandZeroDivisionError. - try and except: Detect and handle errors.
- Specific Exceptions: Catch the types of errors your program expects.
- else: Run code when no exception occurs.
- finally: Run cleanup code whether an exception occurs or not.
- raise: Trigger an exception when an invalid condition is detected.
Example: Handling an Exception
try: number = int(input("Enter a number: ")) print(10 / number) except ValueError: print("Please enter a valid integer.") except ZeroDivisionError: print("You cannot divide by zero.")
If the user enters text instead of an integer, Python raises a ValueError. If the user enters 0, Python raises a ZeroDivisionError. The matching except block handles the problem.
Understanding the try and except Blocks
trycontains code that might raise an exception.excepthandles a matching exception.- You can use multiple
exceptblocks for different exception types.
Example: Using else and finally
try: number = int(input("Enter a number: ")) except ValueError: print("Invalid input.") else: print("Your number is:", number) finally: print("Program execution finished.")
- The
elseblock runs only if no exception occurs in thetryblock. - The
finallyblock runs whether an exception occurs or not.
Example: Raising an Exception
You can raise an exception when a value doesn't meet your program's requirements.
def check_age(age): if age < 0: raise ValueError("Age cannot be negative.") return age print(check_age(20))
Calling check_age(-5) raises a ValueError because a negative age is invalid.
Common Python Exceptions
| Exception | Common cause |
|---|---|
ValueError | A value has an invalid format |
TypeError | An operation uses an inappropriate type |
ZeroDivisionError | A number is divided by zero |
FileNotFoundError | A requested file doesn't exist |
IndexError | A sequence index is out of range |
KeyError | A dictionary key is missing |
Why Is Exception Handling Important?
Exception handling makes programs more reliable, helps provide useful error messages, and prevents expected problems from crashing an application. It is especially useful when working with files, user input, APIs, databases, and automation scripts.
Recommended Learning Path
- Understand errors and exceptions.
- Practice
tryandexcept. - Handle specific exceptions.
- Learn
elseandfinally. - Use
raiseto validate input. - Build programs that handle invalid input safely.
Practice Challenge
Create a calculator that accepts two numbers and an operator. Handle invalid numbers, unsupported operators, and division by zero without displaying a confusing traceback to the user.
Next step: Practice handling different exceptions, then continue to object-oriented programming.
Learn • Build • Grow — Ugenz Academy