Class 12 Notes Computer Science Chap 1 (2024-25)
Class 12 Notes Computer Science Chap 1 (2024-25)
CLASS-12
NOTES
SUBJECT- COMPUTER SCIENCE
CHAPTER-1 EXCEPTION HANDLING
IN PYTHON
Introduction
Exception handling is a mechanism in Python that allows you to manage and respond to runtime errors in a
controlled manner. Instead of letting the program crash when an error occurs, exception handling enables you to
catch and handle errors gracefully.
1. What is an Exception?
• Definition: An exception is an error that occurs during the execution of a program. It disrupts the normal flow of
the program and requires special handling.
• Types of Errors:
o Syntax Errors: Errors in the syntax of the code (e.g., missing colons, mismatched parentheses).
o Runtime Errors: Errors that occur while the program is running (e.g., division by zero, file not found).
• Syntax:
python
Copy code
try:
# Code that might raise an exception
except ExceptionType:
# Code that runs if an exception occurs
• Example:
python
Copy code
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
• Syntax:
python
Copy code
try:
# Code that might raise an exception
except (ExceptionType1, ExceptionType2) as e:
# Code that runs if one of the exceptions occurs
• Example:
python
Copy code
try:
result = int("abc")
except (ValueError, ZeroDivisionError) as e:
print(f"An error occurred: {e}")
Finally Block
• Purpose: The finally block contains code that will always execute, regardless of whether an
exception occurred or not.
• Syntax:
python
Copy code
try:
# Code that might raise an exception
except ExceptionType:
# Code that runs if an exception occurs
finally:
# Code that always runs
• Example:
python
Copy code
try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found.")
finally:
file.close()
3. Raising Exceptions
• Purpose: You can raise exceptions intentionally using the raise keyword.
python
Copy code
raise ExceptionType("Error message")
• Example:
python
Copy code
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero.")
return a / b
try:
result = divide(10, 0)
except ValueError as e:
print(e)
4. Custom Exceptions
• Purpose: You can define your own exception classes to handle specific errors in your application.
• Syntax:
python
Copy code
class CustomError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
try:
raise CustomError("This is a custom error.")
except CustomError as e:
print(e)
• Catch Specific Exceptions: Always catch specific exceptions rather than a generic Exception to avoid masking
other issues.
7. Summary
8. Practice Questions
1. Write a Python program that divides two numbers and handles the ZeroDivisionError exception.
2. How would you handle multiple exceptions in a single try block? Provide an example.
3. Define a custom exception called NegativeNumberError and use it in a function that only accepts positive
numbers.
4. Explain the purpose of the finally block with an example.
5. What are the differences between ValueError and TypeError? Give examples of each.