Exceptions help us find and handle errors in our programs so they don't crash unexpectedly.
Common exception types in Python
Start learning this pattern below
Jump into concepts and practice - no test required
try: # code that might cause an error except ExceptionType: # code to handle the error
Replace ExceptionType with the specific error you want to catch.
You can catch multiple exceptions by listing them in parentheses.
try: x = 1 / 0 except ZeroDivisionError: print("Cannot divide by zero!")
try: value = int('abc') except ValueError: print("Invalid number!")
try: my_list = [1, 2, 3] print(my_list[5]) except IndexError: print("Index is out of range!")
This program asks the user for a number, then divides 10 by that number. It handles errors if the input is not a number or if the number is zero.
try: number = int(input("Enter a number: ")) result = 10 / number print(f"10 divided by {number} is {result}") except ValueError: print("Oops! That is not a valid number.") except ZeroDivisionError: print("Oops! Cannot divide by zero.")
Always catch specific exceptions instead of a general Exception to avoid hiding bugs.
You can use multiple except blocks to handle different errors separately.
Use try-except to keep your program running smoothly even when errors happen.
Exceptions help catch and handle errors in your code.
Common exceptions include ValueError, ZeroDivisionError, and IndexError.
Use try-except blocks to manage errors and keep your program running.
Practice
Solution
Step 1: Understand division by zero
Dividing any number by zero is mathematically undefined and causes an error in Python.Step 2: Identify the exception type
Python raises aZeroDivisionErrorwhen division by zero occurs.Final Answer:
ZeroDivisionError -> Option BQuick Check:
Division by zero = ZeroDivisionError [OK]
- Confusing ZeroDivisionError with ValueError
- Thinking IndexError occurs for division
- Assuming TypeError is raised for zero division
ValueError?Solution
Step 1: Analyze each option for ValueError
int('abc') tries to convert a non-numeric string to int, which causes ValueError.Step 2: Check other options for different exceptions
5 / 0 causes ZeroDivisionError, C causes IndexError, A may cause FileNotFoundError.Final Answer:
int('abc') -> Option DQuick Check:
Invalid int conversion = ValueError [OK]
- Confusing ZeroDivisionError with ValueError
- Assuming file open errors cause ValueError
- Mixing IndexError with ValueError
my_list = [1, 2, 3] print(my_list[3])
Solution
Step 1: Understand list indexing
List indices start at 0, so valid indices for my_list are 0, 1, 2.Step 2: Accessing index 3
Index 3 is out of range, so Python raises an IndexError.Final Answer:
IndexError -> Option AQuick Check:
Out of range index = IndexError [OK]
- Thinking it returns last element
- Assuming None is returned for invalid index
- Confusing IndexError with ValueError
try:
x = int('hello')
except ZeroDivisionError:
print('Cannot divide by zero')Solution
Step 1: Analyze the try block
int('hello') raises ValueError because 'hello' cannot convert to int.Step 2: Check except block
Except block catches ZeroDivisionError, which does not handle ValueError, so error is uncaught.Final Answer:
Wrong exception caught, should catch ValueError -> Option AQuick Check:
Exception type mismatch = catch correct exception [OK]
- Catching wrong exception type
- Assuming code runs without error
- Confusing syntax errors with exception handling
Solution
Step 1: Understand input conversion risks
User input may not be a valid integer, causing ValueError on conversion.Step 2: Check exception handling
try: num = int(input()) except ValueError: print('Invalid number') uses try-except to catch ValueError and print a message, preventing crash.Final Answer:
try-except catching ValueError with message -> Option CQuick Check:
Handle invalid input with ValueError catch [OK]
- Not catching exceptions causing program crash
- Catching wrong exception type like ZeroDivisionError
- Assuming input is always valid integer
