Cross_Column

Monday, 19 January 2026

Exception Handling in Python




Exception Handling in Python

Exception Handling in Python is used to handle runtime errors so that the normal flow of a program does not stop unexpectedly. It helps in writing robust, user-friendly, and error-free programs.


What is an Exception?

An exception is an error that occurs during program execution. When an exception occurs, Python stops normal execution and raises an error.

Example (Without Exception Handling)


x = 10
y = 0
print(x / y)

Error: ZeroDivisionError


Why Exception Handling is Important?

  • Prevents program crash
  • Handles unexpected user input
  • Improves application reliability
  • Provides meaningful error messages

try and except Block

The try block contains code that may cause an exception, and the except block handles the exception.


try:
    x = 10
    y = 0
    print(x / y)
except ZeroDivisionError:
    print("Cannot divide by zero")


Handling Multiple Exceptions


try:
    a = int("abc")
except ValueError:
    print("Invalid value")
except ZeroDivisionError:
    print("Division error")


Using except as

You can capture the exception message using as.


try:
    x = int("abc")
except ValueError as e:
    print("Error:", e)


try – except – else

The else block executes if no exception occurs.


try:
    num = int(input("Enter number: "))
except ValueError:
    print("Invalid input")
else:
    print("You entered:", num)


try – except – finally

The finally block always executes, whether an exception occurs or not.


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


Raising Exceptions (raise)

You can manually raise an exception using the raise keyword.


age = -5

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


User-Defined (Custom) Exceptions

Python allows you to create your own exceptions by extending the Exception class.


class InvalidAgeError(Exception):
    pass

try:
    age = 17
    if age < 18:
        raise InvalidAgeError("Not eligible to vote")
except InvalidAgeError as e:
    print(e)


Common Built-in Exceptions

  • ZeroDivisionError
  • ValueError
  • TypeError
  • IndexError
  • KeyError
  • FileNotFoundError

Exception Handling in Automation Testing


try:
    driver.find_element(By.ID, "login").click()
except Exception as e:
    print("Element not found:", e)

Exception handling is heavily used in:

  • Selenium automation
  • Robot Framework libraries
  • API automation scripts

Best Practices for Exception Handling

  • Catch specific exceptions
  • Avoid using bare except
  • Use finally to close resources
  • Log exceptions instead of ignoring them

Common Interview Questions

  • What is exception handling?
  • Difference between error and exception
  • What is try-except block?
  • What is finally?
  • What is a custom exception?

Conclusion

Exception handling in Python helps you write safe and reliable code. It is a must-have skill for Python developers and automation testers.

👉 Learn more Python tutorials with real examples on way2testing.com

No comments:

Post a Comment

Few More

Multithreading and Multiprocessing in Python

Multithreading and Multiprocessing in Python Python provides powerful tools to perform multiple tasks simultaneously usi...