# How to Handle Errors in Python Effectively 🔍

## 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.

```python
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 :**

```python
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:

```python
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

---

```python
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.

```python
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.

```python
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.")
```

2. **🛒 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` .

```python
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.")
```

3. **📁 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.

```python
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. 🔥💻

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1740900161295/b47cdea0-c856-4aa4-a2b2-d5e597bcbcf1.webp align="center")

---
