0% found this document useful (0 votes)
20 views4 pages

Class 12 Notes Computer Science Chap 1 (2024-25)

This document provides an overview of exception handling in Python, detailing the definition of exceptions, types of errors, and the basic structure for handling exceptions using try and except blocks. It also covers raising exceptions, creating custom exceptions, and best practices for effective exception management. Additionally, practice questions are included to reinforce understanding of the concepts discussed.

Uploaded by

jesal.jani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views4 pages

Class 12 Notes Computer Science Chap 1 (2024-25)

This document provides an overview of exception handling in Python, detailing the definition of exceptions, types of errors, and the basic structure for handling exceptions using try and except blocks. It also covers raising exceptions, creating custom exceptions, and best practices for effective exception management. Additionally, practice questions are included to reinforce understanding of the concepts discussed.

Uploaded by

jesal.jani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Artham Resource

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).

2. Basic Exception Handling

Try and Except Block

• 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!")

JOIN OUR WHATSAPP GROUP


Handling Multiple Exceptions

• 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.

JOIN OUR WHATSAPP GROUP


• Syntax:

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)

5. Common Built-in Exceptions

• Exception: The base class for all exceptions.


• ZeroDivisionError: Raised when dividing by zero.
• FileNotFoundError: Raised when trying to access a file that does not exist.
• ValueError: Raised when a function receives an argument of the right type but inappropriate value.
• IndexError: Raised when accessing an element in a list using an invalid index.

6. Exception Handling Best Practices

• Catch Specific Exceptions: Always catch specific exceptions rather than a generic Exception to avoid masking
other issues.

JOIN OUR WHATSAPP GROUP


• Use finally for Cleanup: Use the finally block for code that must execute regardless of whether an
exception occurred, such as closing files or releasing resources.
• Log Exceptions: Record exceptions to a log file for debugging and monitoring purposes.
• Avoid Empty except: Avoid using except: without specifying the exception type, as it can make debugging
difficult.

7. Summary

• Exception Handling: A method to manage and respond to runtime errors gracefully.


• Try and Except: Basic structure to handle exceptions.
• Finally Block: Ensures code runs regardless of exceptions.
• Raising Exceptions: Use raise to create custom exceptions.
• Custom Exceptions: Define your own exception classes for specific errors.
• Best Practices: Catch specific exceptions, use finally for cleanup, and avoid empty except blocks.

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.

JOIN OUR WHATSAPP GROUP

You might also like