How to Use Try-Except in Python to Handle Errors With Clear Examples



 What Is try-except in Python?

The try-except block in Python is used to catch and handle exceptions (errors) during code execution, preventing the program from crashing.

 Basic Syntax

try:
    # Code that may raise an error
    risky_operation()
except SomeError:
    # Code to run if error occurs
    handle_error()

 Example 1: Handling ZeroDivisionError

try:
    result = 10 / 0
except ZeroDivisionError:
    print("You can't divide by zero!")

Output:

You can't divide by zero!

 Example 2: Catching Multiple Error Types

try:
    number = int("abc")  # Will raise ValueError
except ValueError:
    print("Invalid input: not a number.")

 Example 3: Using else and finally

try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ZeroDivisionError:
    print("Cannot divide by zero.")
except ValueError:
    print("Invalid input. Please enter a number.")
else:
    print("Result:", result)
finally:
    print("This always runs.")

 Why Use try-except?

Benefit Description
Prevent crashes Code runs smoothly even if an error occurs
Handle specific errors Catch and respond to expected problems
Improve user experience Show friendly error messages
Use finally for cleanup tasks E.g., closing files or database connections

 Best Practices

  • Only catch expected exceptions.
  • Avoid catching all errors with a bare except: (unless necessary).
  • Use specific exception types like FileNotFoundError, ValueError, etc.
  • Use finally for cleanup tasks, like closing files or releasing resources.

 Don't Do This (Bad Practice)

try:
    risky_code()
except:
    print("Something went wrong!")  # Too vague!

 Instead, do this:

try:
    risky_code()
except TypeError:
    print("Type error occurred")
except ValueError:
    print("Value error occurred")

0 Comments:

Post a Comment