# P8.4 Python try except else finally सोप्या भाषेत

Source: https://ravindrabagale.com/mr/datascience/py08-python-errors-and-exceptions-try-except-finally-explained/p8-4-python-try-except-else-finally-explained.html
Language: mr (Marathi with English technical terms)

हे का शिकायचं?

Error आला नाही तरच काही करायचं किंवा काहीही झालं तरी शेवटी काही करायचं असतं.

हे काय आहे?

else: error आला नाही तर चालतो. finally: नेहमी चालतो — files बंद करणं, message देणं.

कसं करायचं?

Step 1. try
Step 2. except (एक किंवा अनेक)
Step 3. else
Step 4. finally

उदाहरण A: अनेक except blocks

```python
def get_price(rec):
    try:
        return float(rec["price"])
    except KeyError:
        return "no price field"
    except ValueError:
        return "price is not a number"

print(get_price({"price": "19.99"}))
print(get_price({"name": "Pen"}))
print(get_price({"price": "free"}))
```

Output:

```text
19.99
no price field
price is not a number
```

याचा अर्थ: प्रत्येक error प्रकाराला वेगळा message मिळाला.

उदाहरण B: else आणि finally

```python
def process(qty):
    try:
        per_box = 100 / qty
    except ZeroDivisionError:
        print("Error: quantity is zero")
    else:
        print("Per box:", per_box)
    finally:
        print("Batch logged")

process(4)
process(0)
```

Output:

```text
Per box: 25.0
Batch logged
Error: quantity is zero
Batch logged
```

याचा अर्थ: Error नसताना else चालला आणि finally दोन्ही वेळा चालला.

रवींद्र बागले यांची tip

Files आणि database connections बंद करायला finally (किंवा files chapter मधला `with`) वापरा.
