コンテンツにスキップ

Python例外処理の演習を簡単に解説

[

[](python exception handling exercises)

Python Exception Handling Exercises

Exercise 1: Handling ZeroDivisionError

Write a program that takes two numbers as input from the user and performs division. However, you need to handle the case when the user enters 0 as the second number, which would result in a ZeroDivisionError.

try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = num1 / num2
print("The result of the division is:", result)
except ZeroDivisionError:
print("Error: Cannot divide by 0.")

Exercise 2: Handling ValueError

Write a program that takes an integer input from the user and calculates its square root. However, you need to handle the case when the user enters a non-numeric value, which would result in a ValueError.

import math
try:
num = int(input("Enter a number: "))
result = math.sqrt(num)
print("The square root of", num, "is:", result)
except ValueError:
print("Error: Invalid input. Please enter a valid integer.")

Exercise 3: Handling FileNotFoundError

Write a program that reads the contents of a file specified by the user. However, you need to handle the case when the file does not exist, which would result in a FileNotFoundError.

try:
filename = input("Enter the name of the file: ")
with open(filename, 'r') as file:
contents = file.read()
print("The contents of the file are:\n", contents)
except FileNotFoundError:
print("Error: File not found. Please enter a valid file name.")

Exercise 4: Handling Multiple Exceptions

Write a program that takes two numbers as input from the user and performs various operations like addition, subtraction, multiplication, and division. You need to handle cases where the user enters invalid input or tries to divide by zero.

try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
addition = num1 + num2
subtraction = num1 - num2
multiplication = num1 * num2
division = num1 / num2
print("Addition:", addition)
print("Subtraction:", subtraction)
print("Multiplication:", multiplication)
print("Division:", division)
except ValueError:
print("Error: Invalid input. Please enter valid integers.")
except ZeroDivisionError:
print("Error: Cannot divide by 0.")

In this tutorial, we have covered various exercises related to handling exceptions in Python. These exercises provide hands-on practice on how to handle different types of exceptions such as ZeroDivisionError, ValueError, and FileNotFoundError. By going through these step-by-step exercises, you will gain a better understanding of how to use try-except blocks to handle errors and exceptions in your Python programs. Remember, exception handling is a crucial aspect of writing robust and error-free code, and these exercises will help you sharpen your skills in this area.

Keep practicing and exploring different scenarios to strengthen your knowledge of Python exception handling. Happy coding!