Error Handling in Python

Introduction

Programming में errors आना सामान्य बात है, लेकिन अगर इन्हें handle न किया जाए तो program crash हो सकता है।

Error Handling का मतलब है program में आने वाले errors को इस तरह manage करना कि program smoothly चलता रहे और user को proper message मिले।

यह concept real-world applications के लिए बहुत important है।

Error Handling क्या होता है

Error Handling वह process है, जिसके द्वारा हम program में आने वाले errors को control और manage करते हैं।

Python में इसके लिए mainly try, except, else और finally blocks का उपयोग किया जाता है।

Error और Exception में अंतर

  • Error → coding mistake (syntax error)
  • Exception → runtime error (program चलाते समय)

Basic Structure

try:
# risky code
except:
# error handling

कैसे काम करता है

  1. try block में code run होता है
  2. अगर error आता है → except block execute होता है
  3. अगर error नहीं आता → try block normally complete होता है

Example

try:
a = int(input("Enter number: "))
print(10 / a)
except:
print("Error occurred")

Specific Error Handling

try:
a = int(input("Enter number: "))
print(10 / a)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Invalid input")

Multiple except blocks

हम अलग-अलग errors को अलग-अलग तरीके से handle कर सकते हैं।

else block

अगर error नहीं आता, तो else block execute होता है।

try:
num = int(input("Enter number: "))
print(num)
except:
print("Error")
else:
print("No error")

finally block

यह block हमेशा execute होता है।

try:
print("Hello")
except:
print("Error")
finally:
print("Program finished")

Real-life Example: Login system

try:
password = input("Enter password: ")
if password != "1234":
raise Exception("Wrong Password")
print("Login Successful")
except Exception as e:
print(e)

Real-life Example: Safe file access

try:
file = open("data.txt", "r")
print(file.read())
except FileNotFoundError:
print("File not found")
finally:
print("Done")

raise keyword

हम खुद भी error generate कर सकते हैं।

age = -5if age < 0:
raise ValueError("Age cannot be negative")

Common mistakes

  1. सभी errors को generic except से handle करना
  2. useful error message न देना
  3. try block में unnecessary code डालना

Mini Program

try:
num = int(input("Enter number: "))
print(100 / num)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Invalid input")
finally:
print("Program ended")

Summary

Error Handling Python में program को safe और stable बनाता है।
यह ensure करता है कि errors आने पर भी program crash न हो और सही output दे सके।

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top