Understanding exceptions and their types
Understanding Exceptions and Their Types
This topic provides an introduction to exceptions in Python, their purpose, and common types of exceptions. It covers the basics of exception handling and error management in Python programming.
YouTube Video Link: Understanding Exceptions and Their Types in Python - Please note that the provided link is a placeholder. You can search for relevant videos on popular platforms like YouTube or other online learning platforms.
Examples
Example 1: Division by Zero Exception
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero!")
Example 2: Index Error
my_list = [1, 2, 3]
try:
print(my_list[5])
except IndexError:
print("Error: Index out of range!")
Example 3: Value Error
try:
num = int("abc")
except ValueError:
print("Error: Invalid value!")
Example 4: Type Error
try:
result = "Hello" + 42
except TypeError:
print("Error: Incompatible types!")
Example 5: File Not Found Error
try:
file = open("nonexistent_file.txt", "r")
except FileNotFoundError:
print("Error: File not found!")
Exercises
Exercise 1: Write a program that takes two numbers as input from the user and performs division. Handle the ZeroDivisionError exception and display an error message if the second number is zero.
Exercise 2: Write a program that prompts the user to enter an integer and converts it to a string. Handle the ValueError exception and display an error message if the input cannot be converted to an integer.
Exercise 3:
Create a function called get_value
that takes a dictionary and a key as input. The function should return the value associated with the given key. Handle the KeyError exception and return "Key not found" if the key is not present in the dictionary.
Exercise 4: Write a program that reads a list of integers from the user and calculates the average. Handle the ValueError exception when converting user input to integers and display an error message for invalid input.
Exercise 5: Write a program that opens a file specified by the user and displays its content. Handle the FileNotFoundError exception and display an error message if the file does not exist.
Using Try-Except Blocks
This topic focuses on the usage of try-except blocks in Python for handling exceptions. It covers the syntax, purpose, and best practices of using try-except blocks to handle potential errors and exceptions in code.
YouTube Video Link: Using Try-Except Blocks in Python - Please note that the provided link is a placeholder. You can search for relevant videos on popular platforms like YouTube or other online learning platforms.
Examples
Example 1: Handling a Specific Exception
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
Example 2: Handling Multiple Exceptions
try:
num = int(input("Enter a number: "))
index = int(input("Enter an index: "))
result = num / index
print("Result:", result)
my_list = [1, 2, 3]
print("Element at index {}: {}".format(index, my_list[index]))
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except IndexError:
print("Error: Index out of range!")
Example 3: Handling All Exceptions
try:
num = int(input("Enter a number: "))
result = 100 / num
print("Result:", result)
except Exception as e:
print("An error occurred:", str(e))
Exercises
Exercise 1: Write a program that prompts the user to enter a string and converts it to an integer. Use a try-except block to handle the ValueError exception and display an error message if the input cannot be converted.
Exercise 2:
Create a function called divide_numbers
that takes two numbers as input and returns the result of their division. Use a try-except block to handle the ZeroDivisionError exception and return 0 if the second number is zero.
Exercise 3: Write a program that reads a list of integers from the user and calculates their sum. Use a try-except block to handle the ValueError exception and display an error message for invalid input.
Exercise 4:
Create a function called get_value
that takes a dictionary and a key as input. The function should return the value associated with the given key. Use a try-except block to handle the KeyError exception and return None if the key is not found.
Exercise 5: Write a program that opens a file specified by the user and displays its content. Use a try-except block to handle the FileNotFoundError exception and display an error message if the file does not exist.
Handling Specific Exceptions
This topic focuses on handling specific exceptions in Python. It covers how to handle different types of exceptions based on their specific error conditions. You'll learn how to use multiple except blocks to target specific exceptions and provide appropriate error handling for each case.
YouTube Video Link: Handling Specific Exceptions in Python - Please note that the provided link is a placeholder. You can search for relevant videos on popular platforms like YouTube or other online learning platforms.
Examples
Example 1: Handling ZeroDivisionError
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
Example 2: Handling FileNotFoundError
try:
filename = input("Enter a filename: ")
with open(filename, "r") as file:
content = file.read()
print("File content:", content)
except FileNotFoundError:
print("Error: File not found!")
Example 3: Handling ValueError and TypeError
try:
num = int(input("Enter a number: "))
result = 100 / num
print("Result:", result)
my_list = [1, 2, 3]
print("Element at index {}: {}".format(num, my_list[num]))
except ValueError:
print("Error: Invalid input!")
except TypeError:
print("Error: Unsupported operation!")
Exercises
Exercise 1: Write a program that prompts the user to enter their age and converts it to an integer. Handle the ValueError exception and display an error message if the input is not a valid age.
Exercise 2:
Create a function called divide_numbers
that takes two numbers as input and returns the result of their division. Handle the ZeroDivisionError exception and return 0 if the second number is zero.
Exercise 3: Write a program that reads a list of integers from the user and calculates their average. Handle the ValueError exception and display an error message for invalid input.
Exercise 4:
Create a function called get_value
that takes a dictionary and a key as input. The function should return the value associated with the given key. Handle the KeyError exception and return None if the key is not found.
Exercise 5: Write a program that opens a file specified by the user and displays the first five lines. Handle the FileNotFoundError exception and display an error message if the file does not exist.
Raising Custom Exceptions
This topic focuses on raising custom exceptions in Python. It covers how to create your own exception classes by inheriting from the base Exception class. You'll learn how to define custom exception types and raise them in your code to handle specific error conditions or situations.
YouTube Video Link: Raising Custom Exceptions in Python - Please note that the provided link is a placeholder. You can search for relevant videos on popular platforms like YouTube or other online learning platforms.
Examples
Example 1: Raising a Custom Exception
class CustomException(Exception):
pass
def divide_numbers(num1, num2):
if num2 == 0:
raise CustomException("Cannot divide by zero!")
return num1 / num2
try:
result = divide_numbers(10, 0)
print("Result:", result)
except CustomException as e:
print("Error:", str(e))
Example 2: Creating a Custom Exception Hierarchy
class CustomException(Exception):
pass
class InvalidInputError(CustomException):
pass
class OutOfRangeError(CustomException):
pass
def process_input(value):
if not isinstance(value, int):
raise InvalidInputError("Invalid input! Expected an integer.")
if value < 1 or value > 100:
raise OutOfRangeError("Input value is out of range!")
# Process the input value
try:
process_input("abc")
except CustomException as e:
print("Error:", str(e))
Example 3: Raising Custom Exceptions with Additional Information
class InsufficientFundsError(Exception):
def __init__(self, amount, balance):
self.amount = amount
self.balance = balance
message = f"Insufficient funds! Available balance: {balance}, Required amount: {amount}"
super().__init__(message)
def withdraw(amount, balance):
if amount > balance:
raise InsufficientFundsError(amount, balance)
# Process the withdrawal
try:
withdraw(1000, 500)
except InsufficientFundsError as e:
print("Error:", str(e))
print("Please deposit additional funds.")
Exercises
Exercise 1:
Create a custom exception class called InvalidPasswordError
that is raised when a user enters an invalid password. The password is considered invalid if it is less than 8 characters long. Write a program that prompts the user to enter a password and raises this exception if the password is invalid.
Exercise 2:
Define a custom exception class called InvalidEmailError
that is raised when an email address is not in the correct format. The email address should have the format: <username>@<domain>.<extension>
. Write a program that takes an email address as input and raises this exception if the email address is not in the correct format.
Exercise 3:
Create a custom exception class called InvalidCredentialsError
that is raised when a user enters invalid login credentials. Write a function called login
that takes a username and password as input and raises this exception if the login credentials are invalid.
Exercise 4:
Define a custom exception class called FileNotFoundError
that is raised when a file is not found. Write a program that prompts the user to enter a filename and raises this exception if the file is not found.
Exercise 5:
Create a custom exception class called InvalidInputError
that is raised when an input value is not in a specified range. Write a function called validate_age
that takes an age as input and raises this exception if the age is not between 18 and 65 (inclusive).
Last updated
Was this helpful?