Python try-except Block
In Python, try-except is used to handle exceptions and errors that may occur during program execution. It helps prevent program crashes and allows smooth error handling.
Python में, try-except का उपयोग errors को handle करने के लिए किया जाता है ताकि प्रोग्राम crash न हो और smooth execution हो सके।
Syntax:
try:
# code that may raise an error
except ErrorType:
# code to handle the error
Example 1: Handle Division Error
try:
num1 = 10
num2 = 0
print(num1 / num2)
except ZeroDivisionError:
print("You cannot divide by zero!")
This example catches the division by zero error and prints a user-friendly message.
यह उदाहरण zero से divide करने की गलती को पकड़ता है और message दिखाता है।
Example 2: Multiple except blocks
try:
x = int("hello")
except ValueError:
print("Invalid value: not a number")
except TypeError:
print("Type mismatch")
This example shows how you can catch specific exceptions separately.
यह उदाहरण दिखाता है कि आप अलग-अलग errors को अलग-अलग तरीके से handle कर सकते हैं।
Example 3: Generic except block
try:
print(10 / 0)
except:
print("Some error occurred")
Avoid using generic except
unless necessary. It's better to catch specific exceptions.
सिर्फ except
का उपयोग करना ठीक नहीं है, specific errors पकड़ना बेहतर है।
Example 4: else and finally
try:
print("All good!")
except:
print("Error occurred")
else:
print("No errors found.")
finally:
print("This will always execute.")
else
runs if no exception occurs. finally
always runs.
else
तब चलता है जब कोई error नहीं होता और finally
हमेशा चलता है।