In the example below, I’ve written a simple Python script that demonstrates and handles various built-in exceptions. This script involves file operations, data processing, and basic user input to trigger and handle several common exceptions.
Example Code
def main():
try:
# File operation exception
file_path = input("Enter the path of the file to read: ")
with open(file_path, 'r') as file:
print(file.read())
# Import module exception
import some_unknown_module
# KeyError and TypeError
data = {'a': 1, 'b': 2}
key = input("Enter the key to access: ")
print("Value:", data[int(key)]) # Triggers KeyError and TypeError
# ValueError
number = int(input("Enter an integer number: "))
# ZeroDivisionError
print("100 divided by your number is:", 100 / number)
except FileNotFoundError:
print("Error: The file was not found.")
except ImportError:
print("Error: The module does not exist.")
except KeyError:
print("Error: The key does not exist in the dictionary.")
except ValueError:
print("Error: Invalid input. Please enter a valid integer.")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except TypeError as e:
print("Error: Type error -", e)
except Exception as e:
print("An unexpected error occurred:", e)
if __name__ == "__main__":
main()Exception Handling Explained
FileNotFoundError
Raised when theopen()function fails to find the file path entered by the user.ImportError
Triggered when attempting to import a module that does not exist.KeyErrorandTypeErrorKeyError: Raised when trying to access a dictionary with a key that does not exist.TypeError: Raised when using an incorrect type, such as attempting to use an integer as a dictionary key when it expects a string.ValueError
Occurs when a user enters a non-integer value that the program attempts to convert to an integer.ZeroDivisionError
Triggered when the user inputs0as a divisor.General
Exception
Captures any other exceptions not explicitly handled by the preceding exception blocks.
Benefits of This Script
This script is a practical example of how to identify and handle multiple common exceptions in real-world programs. The use of appropriate error messages provides feedback to the user, improving the program’s robustness and user experience without crashing the program.