0% found this document useful (0 votes)
3 views

Untitled Document (37)

Uploaded by

kylemessi001
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)
3 views

Untitled Document (37)

Uploaded by

kylemessi001
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/ 7

Detailed Lecture on Exceptions and Error Handling

1. Introduction to Exceptions

In programming, exceptions represent errors that occur during the


execution of a program, disrupting the normal flow of instructions.

Types of Errors:

1. Syntax Errors: Errors in the structure of the code, detected before


the program runs.
○ Example: Missing a colon in an if statement.
2. Runtime Errors: Errors that occur during execution, like dividing by
zero or accessing an out-of-range index.

Why Are Exceptions Important?

● Exceptions help handle unexpected issues gracefully, preventing


program crashes.
● They make your program fault-tolerant, improving user experience.

2. Handling Errors with Conditional Statements

Traditionally, conditional statements like if-else are used to handle


predictable errors.

Example:

import re

user_input = input("Enter a year: ")


if re.match(r"^\d{4}$", user_input): # Regex for a
4-digit year

year = int(user_input)

print("Your chosen year:", year)

else:

print("Error: Not a valid year.")

Limitations:

● Can become complex and hard to maintain for nested conditions.


● Not suitable for handling unforeseen runtime errors, like file access
failures or division by zero.

3. Exception Handling in Python

Python provides a structured way to handle errors using the try and
except blocks.

Basic Structure:

try:

# Code that may cause an exception

risky_operation()

except ExceptionType:
# Code to handle the exception

Example: Handling Division by Zero

try:

num1 = int(input("Enter numerator: "))

num2 = int(input("Enter denominator: "))

result = num1 / num2

print("Result:", result)

except ZeroDivisionError:

print("Error: Division by zero is not allowed.")

4. Handling Multiple Exceptions

When a block of code may raise different types of exceptions, you can use
multiple except blocks.

Example:

try:

num1 = int(input("Enter numerator: "))


num2 = int(input("Enter denominator: "))

result = num1 / num2

print("Result:", result)

except ZeroDivisionError:

print("Error: Cannot divide by zero.")

except ValueError as ve:

print("Error: Invalid input. Please enter numbers


only.")

print("Details:", ve)

Key Points:

● Each except block is specific to an exception type.


● The as keyword stores the exception details in a variable (e.g., ve).

5. Raising Custom Exceptions

In addition to handling exceptions, you can raise your own exceptions to


enforce constraints or signal errors.

Example: Validating User Input

try:

rating = int(input("Rate your favorite movie (1-5):


"))
if rating < 1 or rating > 5:

raise ValueError("Rating must be between 1 and


5.")

print("Thank you! You rated:", rating)

except ValueError as ve:

print("Error:", ve)

When to Raise Exceptions?

● To enforce business rules or input validation.


● When returning an error directly would cause ambiguity.

6. Common Python Exceptions

Here are some frequently encountered exceptions in Python:

Exception Description

ZeroDivisi Raised when dividing by zero.


onError

ValueError Raised when a function receives an argument of the


correct type but invalid value.

TypeError Raised when an operation or function is applied to an


object of inappropriate type.
IndexError Raised when attempting to access an index outside the
range of a list.

KeyError Raised when trying to access a dictionary key that


doesn’t exist.

7. Best Practices for Error Handling

1. Handle Specific Exceptions:


○ Avoid generic except Exception: blocks unless absolutely
necessary.
○ Specific handlers provide clarity and avoid masking errors.
2. Log Errors for Debugging:
○ Use logging libraries to capture and store error details for
troubleshooting.
import logging

logging.basicConfig(filename='error.log',
level=logging.ERROR)

try:

result = 10 / 0

except ZeroDivisionError as e:

logging.error("Error occurred: %s", e)

3. Avoid Overusing Exceptions:


○ Exceptions should handle unexpected errors, not replace
conditional logic for expected outcomes.
4. Use finally for Cleanup:
○ The finally block executes regardless of whether an
exception occurs, making it ideal for cleanup tasks.
try:

file = open("data.txt", "r")

data = file.read()

except FileNotFoundError:

print("File not found!")

finally:

if 'file' in locals() and not file.closed:

file.close()

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy