Python Guide Sidebar

Python – Exception Handling

Introduction to Exception Handling in Python

Exception handling in Python is a crucial mechanism that helps in managing runtime errors efficiently. Instead of crashing the program when an error occurs, Python allows developers to handle these errors gracefully using try-except blocks. This approach ensures that programs continue executing without unexpected interruptions.

Python Exception Handling
Why is Exception Handling Important?

Exception handling is essential for:

  • Preventing program crashes – Ensures smooth execution despite errors.
  • Improving user experience – Provides meaningful error messages instead of abrupt termination.
  • Maintaining data integrity – Prevents data corruption by handling exceptions properly.
  • Debugging and logging – Helps in tracking errors systematically.
Types of Errors in Python

Before diving into exception handling, let’s understand the common types of errors in Python:

1. Syntax Errors – Occur due to incorrect Python syntax.pythonCopyEdit

print("Hello World" # Missing closing parenthesis  

2. Logical Errors – Do not crash the program but produce incorrect results.

3. Runtime Errors (Exceptions) – Happen during execution and require handling.

Handling Exceptions Using try-except

The try-except block helps catch and handle exceptions gracefully.

Basic Example

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

Explanation:

  1. The try block contains the code that may raise an exception.
  2. The except block catches specific exceptions and executes appropriate error-handling code.

Handling Multiple Exceptions

Python allows handling multiple exceptions within a single try-except block.

try:
    num = int(input("Enter a number: "))
    print(10 / num)
except (ZeroDivisionError, ValueError) as e:
    print(f"An error occurred: {e}")

When to Use Multiple Except Blocks?

  • When different errors need different handling approaches.
  • When specific error messages or corrective actions are required.
Using else and finally in Exception Handling

Python provides additional clauses like else and finally in try-except blocks.

Example: Using else and finally

try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ZeroDivisionError:
    print("Error: Cannot divide by zero.")
else:
    print(f"Result: {result}")
finally:
    print("Execution complete.")

Explanation:

  • The else block executes when no exceptions occur.
  • The finally block always runs, regardless of whether an exception was raised.
Raising Custom Exceptions

Python allows developers to raise their own exceptions using the raise keyword.

def check_age(age):
    if age < 18:
        raise ValueError("Age must be 18 or above.")
    print("Access granted.")

try:
    check_age(16)
except ValueError as e:
    print(e)
Use Cases of Custom Exceptions:
  • Validating user input
  • Handling business logic-related errors
Common Exceptions in Python

Python has many built-in exceptions, each representing a specific error condition. Some of the most common ones include:

Exception NameDescription
BaseExceptionThe base class for all built-in exceptions.
ExceptionThe base class for all non-exit exceptions.
ArithmeticErrorBase class for all errors related to arithmetic operations.
ZeroDivisionErrorRaised when a division or modulo operation is performed with zero as the divisor.
OverflowErrorRaised when a numerical operation exceeds the maximum limit of a data type.
FloatingPointErrorRaised when a floating-point operation fails.
AssertionErrorRaised when an assert statement fails.
AttributeErrorRaised when an attribute reference or assignment fails.
IndexErrorRaised when a sequence subscript is out of range.
KeyErrorRaised when a dictionary key is not found.
MemoryErrorRaised when an operation runs out of memory.
NameErrorRaised when a local or global name is not found.
OSErrorRaised when a system-related operation (like file I/O) fails.
TypeErrorRaised when an operation or function is applied to an object of inappropriate type.
ValueErrorRaised when a function receives an argument of the right type but an inappropriate value.
ImportErrorRaised when an import statement has issues.
ModuleNotFoundErrorRaised when a module cannot be found.

Additional Topics:


Interview Questions:

1. What is the difference between syntax errors and exceptions?(TCS)

  • Exceptions are runtime errors that occur during execution, but they can be handled using try-except.
  • Syntax errors occur when the code violates Python’s syntax rules, and they prevent execution.

2. Explain the difference between try-except and try-finally.(Infosys)

  • The try-finally block ensures that the finally section executes regardless of whether an exception occurs.
  • The try-except block catches and handles specific exceptions, preventing the program from crashing.

3. How would you implement custom exception handling in a Python-based web application?(Amazon)

  • Implement try-except in critical sections of the application to catch and handle the exception.
  • Create a custom exception class by inheriting from Exception.
  • Use raise to trigger the exception when necessary.

Quizzes Handling