How to Handle Errors in Python Effectively π
Mastering Error Handling in Python: A Complete Guide with Real-World Examples
What is error handling ?
Error handling is a process that ensures the smooth execution of a program even when an error occurs. As the name suggests, error handling manages errors and provides appropriate error messages, which help in understanding the error and aid in debugging.
number = input("Enter the number : ")
for i in range(1, 11):
print(f"{number} x {i} = {int(number) * i}")
The above code prints the multiplication table of a number provided by the user. However, if the user enters letters or words instead of a number, the code will not execute and will result in an error.
β Error :
Enter the number : rohit
Traceback (most recent call last):
print(f"{number} x {i} = {int(number) * i}")
^^^^^^^^^^^ValueError: invalid literal for int() with base 10: 'rohit'
π οΈ try - except
To prevent this error, you should use exception handling with try-except, like this:
try:
number = input("Enter the number : ")
for i in range(1, 11):
print(f"{number} x {i} = {int(number) * i}")
# Gives errors by the systemexcept Exception as e:
print(e)
# Error : output : invalid literal for int() with base 10: 'rohit'
π Custom Error Message
try:
number = input("Enter the number : ")
for i in range(1, 11):
print(f"{number} x {i} = {int(number) * i}")
# The line below displays a custom message when an error occurs.# A ValueError exception occurs when the data type is correct,# but the value itself is inappropriate.except ValueError:
print("Error Occurred (Custom Error Handling Message)")
π Finally
finally
is a keyword that always executes, regardless of whether the code inside the try block runs successfully or encounters an error.
try:
l = [1, 5, 6, 7]
i = int(input("Enter the index : "))
print(l[i])
except:
print("Some error occurred")
finally:
print("I am always executed")
π Real World Application
- π§ ATM Transactions
If the atm pin is not 4 digit then it will raise ValueError
. and as you can see in below code βThank you for using out serviceβ will always prints as it is thanking customer no matter what is result.
try:
pin = input("Enter your 4-digit PIN: ")
if len(pin) != 4 or not pin.isdigit():
raise ValueError("Invalid PIN. Please enter a 4-digit number.")
print("PIN accepted. Processing your transaction...")
except ValueError as e:
print(e)
finally:
print("Thank you for using our service.")
- π Online Shopping Payment
Program will take credit card pin and if the number is not 16 digit or number is not in numeric type it will raise ValurError
.
try:
card_number = input("Enter your credit card number: ")
if len(card_number) != 16 or not card_number.isdigit():
raise ValueError("Invalid card number! Must be 16 digits.")
print("Payment processing...")
except ValueError as e:
print(e)
finally:
print("Transaction attempt recorded.")
- π File Handling in Applications
Before attempting to read a file, the program checks for its existence in the directory. If the file is missing, a FileNotFoundError
is triggered.
try:
file = open("data.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("Error: The file does not exist.")
finally:
print("File operation completed.")
πΉ Error handling is crucial for building robust applications. Mastering it will help you create reliable programs that provide a great user experience! π
π’ Stay tuned! I'll be sharing more insightful blogs like this to help you level up your coding skills. π₯π»