1. Introduction
- Why Study This Topic?
Exceptions occur when an error disrupts the normal flow of a program. Python provides built-in mechanisms to handle exceptions, preventing crashes and improving program reliability. Understanding exception handling is crucial for writing robust and error-free code. - What Will Be Covered?
- What are exceptions?
- Common built-in exceptions in Python.
- Handling exceptions with
try-except
. - Using
finally
andelse
with exceptions. - Raising custom exceptions.
2. Detailed Content
What are Exceptions?
Exceptions are runtime errors that occur due to invalid operations, such as dividing by zero or accessing an undefined variable. Without proper handling, exceptions cause program termination. Understanding exceptions is vital for debugging.
2.1 Common Built-in Exceptions
Exception | Description |
---|---|
ZeroDivisionError | Raised when a number is divided by zero. |
ValueError | Occurs when an invalid value is passed to a function. |
TypeError | Raised when an operation is applied to an incompatible data type. |
IndexError | Occurs when trying to access an invalid index in a list. |
KeyError | Raised when trying to access a non-existent dictionary key. |
FileNotFoundError | Occurs when attempting to open a non-existent file. |
NameError | Raised when referencing an undefined variable. |
AttributeError | Occurs when an invalid attribute is accessed on an object. |
2.2 Handling Exceptions with Try-Except
pythonCopyEdittry:
num = int(input("Enter a number: "))
result = 10 / num
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Invalid input. Please enter a number.")
2.3 Using Finally for Cleanup
pythonCopyEdittry:
file = open("example.txt", "r")
content = file.read()
finally:
file.close()
print("File closed.")
The finally
block ensures that the file closes regardless of errors. This handling of exceptions guarantees resource release.
2.4 Using Else with Try-Except
pythonCopyEdittry:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
else:
print(f"Result: {result}") # Executes if no exception occurs
2.5 Raising Custom Exceptions
pythonCopyEditclass NegativeNumberError(Exception):
"""Exception raised for negative numbers."""
pass
num = -5
if num < 0:
raise NegativeNumberError("Negative numbers are not allowed.")
3. Summary
- Exceptions help in handling errors gracefully without program crashes.
- Python provides built-in exceptions, and users can define custom exceptions for better error management.
try-except-finally-else
structures allow efficient error handling through exceptions management.
4. Learning Outcomes
After completing this topic, learners will be able to:
- Identify and handle common Python exceptions.
- Use
try-except-finally
to prevent program crashes. This is essential for exceptions. - Raise and define custom exceptions.
5. Common Interview Questions
- What is an exception in Python?
- A runtime error that disrupts program execution.
- What is the difference between syntax errors and exceptions?
- Syntax errors occur during compilation, while exceptions occur at runtime.
- Can we have multiple except blocks?
- Yes, multiple
except
blocks can handle different exception types.
- Yes, multiple
6. Practice Exercises
- Write a Python script to handle
ZeroDivisionError
andValueError.
These are common exceptions. - Implement a function that raises a
FileNotFoundError
when a file is missing. - Create a custom exception for handling invalid user input.
7. Additional Resources
- Python Exception Handling Documentation
- Tutorials on Real Python and GeeksforGeeks, offering deeper insights into exceptions handling.