Python Exceptions and Error Handling
1. What is an Exception in Python? How is it Different from an Error?
An exception in Python is an unexpected event that occurs during program execution, disrupting the normal
flow of
the program. It usually arises due to logical issues, such as division by zero, invalid operations, or accessing
an
undefined variable.
An error includes both syntax errors and runtime exceptions:
- Syntax Errors: Occur due to incorrect syntax (e.g., missing colons, indentation errors).
- Exceptions (Runtime Errors): Occur when an operation is not possible during execution.
Example of Syntax Error:
if True
print("Hello") # Missing colon (SyntaxError)
Example of Exception:
a = 10 / 0 # ZeroDivisionError (Exception)
------------------------------------------------------------
2. Five Built-in Exceptions in Python
1. ZeroDivisionError - Raised when attempting to divide by zero.
print(10 / 0) # ZeroDivisionError
2. TypeError - Raised when an operation is performed on incompatible data types.
print(10 + "hello") # TypeError
3. IndexError - Raised when trying to access an index that is out of range.
my_list = [1, 2, 3]
print(my_list[5]) # IndexError
4. KeyError - Raised when trying to access a dictionary key that does not exist.
my_dict = {"name": "Alice"}
print(my_dict["age"]) # KeyError
5. ValueError - Raised when an operation receives an argument of the right type but inappropriate value.
num = int("abc") # ValueError
------------------------------------------------------------
3. Handling Exceptions in Python
Using try-except block:
try:
a = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
Handling Multiple Exceptions:
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input!")
------------------------------------------------------------
4. Purpose of try-except Block in Python
- Prevents abrupt program termination.
- Allows error handling without stopping execution.
- Provides a way to execute alternative code when an error occurs.
Example:
try:
x = int(input("Enter a number: "))
print(10 / x)
except ZeroDivisionError:
print("You cannot divide by zero!")
except ValueError:
print("Invalid input.")
finally:
print("This will always execute.")
------------------------------------------------------------
5. What is a ZeroDivisionError and How Can It Be Avoided?
A ZeroDivisionError occurs when a number is divided by zero.
Example:
print(10 / 0) # ZeroDivisionError
To avoid it:
num = int(input("Enter a number: "))
if num == 0:
print("Cannot divide by zero!")
else:
print(10 / num)
------------------------------------------------------------
6. How Does Python Handle Exceptions Using the raise Keyword?
The raise keyword is used to manually trigger an exception.
Example:
def check_age(age):
if age < 18:
raise ValueError("Age must be 18 or older")
else:
print("You are allowed.")
Another example:
try:
raise ZeroDivisionError("Custom message: Division by zero is not allowed")
except ZeroDivisionError as e:
print(e)