How to Handle Errors in Python Effectively πŸ”

Rohit RajvaidyaRohit Rajvaidya
3 min read

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


  1. 🏧 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.")
  1. πŸ›’ 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.")
  1. πŸ“ 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. πŸ”₯πŸ’»


0
Subscribe to my newsletter

Read articles from Rohit Rajvaidya directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rohit Rajvaidya
Rohit Rajvaidya