Error and Exception Handling.
"t is common sense to take a method and try it. If it fails,admit it frankly and try another. But above all, try something"
— Franklin Delano Roosevelt
Common
- Handling ZeroDivisionError: Write a program that takes two numbers as input and performs division. Use a try-except block to handle the
ZeroDivisionError
in case the denominator is zero. Display a custom message when this exception occurs. - Handling Multiple Exceptions: Create a program that takes two inputs: a number and a string. Use a try-except block to handle
ValueError
(if the input cannot be converted to an integer) andTypeError
(if trying to perform an invalid operation). Display appropriate messages for each exception. - Using Finally Block: Write a program that reads from a file and prints its content. Use a try-except block to handle
FileNotFoundError
if the file does not exist. Ensure the file is closed properly using afinally
block, whether the exception occurs or not. - Raising Custom Exceptions: Define a custom exception called
AgeTooSmallError
. Write a program that checks the age input by the user. If the age is below 18, raise theAgeTooSmallError
with a custom error message. Use a try-except block to catch and display the exception message. - Handling IndexError: Write a program that asks the user for an index and tries to access that index in a list. Use a try-except block to handle the
IndexError
if the user enters an invalid index. Print an error message if the index is out of range. - Exception Chaining: Write a program where one exception causes another exception. For instance, inside a try block, raise a
ValueError
and then, in the except block, raise aTypeError
. Use exception chaining to display both exceptions together. - Handling KeyError in Dictionaries: Create a dictionary that stores student names and their scores. Write a program that takes a student's name as input and retrieves their score. Use a try-except block to handle the
KeyError
if the student’s name is not found in the dictionary, and display a custom error message. - Using Else Block with Exceptions: Write a program that asks the user for a number and converts it to an integer. Use a try-except block to handle
ValueError
if the input is not a valid number. Include anelse
block to display a success message when no exception occurs. - Nested Try-Except Blocks: Write a program that takes two numbers and performs division. Inside the try block, use another nested try-except block to handle
ZeroDivisionError
andValueError
. Ensure the outer block catches any other unexpected exceptions and displays a generic error message. - Re-raising Exceptions: Write a program where a function performs a division operation. Use a try-except block to catch any
ZeroDivisionError
but then re-raise the exception after displaying a message. The exception should propagate to the caller of the function.