B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP Python Exception Handling Tutorial | LiveCodeProgramming

Exception Handling in Python

In Python, exception handling is used to handle runtime errors gracefully. It prevents program crashes and allows you to manage errors properly.

Python में exception handling का उपयोग runtime errors को संभालने के लिए किया जाता है ताकि प्रोग्राम क्रैश न हो और errors को सही तरीके से manage किया जा सके।

Why Use Exception Handling?

  • To avoid program crashes due to unexpected errors.
  • To provide meaningful error messages.
  • To handle user input and file operations safely.
  • अनपेक्षित errors के कारण प्रोग्राम को crash होने से बचाने के लिए।
  • सार्थक error messages दिखाने के लिए।
  • user input और file operations को सुरक्षित रूप से handle करने के लिए।

Syntax:

try:
    # code that may raise an error
except SomeException:
    # handle the error

Example 1: Handle ZeroDivisionError

try:
    a = 5
    b = 0
    print(a / b)
except ZeroDivisionError:
    print("Cannot divide by zero")

Here, we handled division by zero error using try-except.

यहाँ हमने try-except से divide by zero error को handle किया है।

Example 2: Using finally block

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

finally block runs whether an exception occurs or not.

finally block हमेशा run होता है, चाहे error हो या नहीं।

Common Built-in Exceptions

  • ZeroDivisionError – Dividing by zero
  • FileNotFoundError – File not found
  • TypeError – Wrong data type used
  • ValueError – Invalid value
  • IndexError – List index out of range
  • ZeroDivisionError – शून्य से भाग देना
  • FileNotFoundError – फ़ाइल नहीं मिली
  • TypeError – गलत डेटा टाइप
  • ValueError – अमान्य मान
  • IndexError – लिस्ट का गलत index