Essential cookies keep authentication working. With your permission, we also use analytics cookies to understand and improve the product. Read our Privacy Policy

DataEngPrep.tech
QuestionsPracticeAI CoachDashboardPricingBlog
ProLogin
Home/Questions/Python/Coding/How do you handle exceptions in Python? Provide an example.

How do you handle exceptions in Python? Provide an example.

Python/Codingeasy2 min read

Reviewed by Aditya Kumar · Last reviewed 2026-03-24

Python handles exceptions using the try , except , else , and finally blocks. This mechanism is crucial for building robust data pipelines, preventing crashes, and ensuring critical operations like…

🤖 Analyze Your Answer
Frequency
Low
Asked at 2 companies
Category
179
questions in Python/Coding
Difficulty Split
127E|24M|28H
in this category
Total Bank
1,863
across 7 categories
Asked at these companies
AltimetrikInfosys
Interview Pro Tip

Red Flag: Empty `except: pass` or catching `Exception` and not re-raising. Pro-Move: 'I catch specific exceptions, log with stack traces, use finally for connection cleanup, and have a top-level handler for unhandled exceptions in long-running services.'

Key Concepts Tested
python

Why This Question Matters

This easy-level Python/Coding question appears frequently in data engineering interviews at companies like Altimetrik, Infosys. While less common, it tests deeper understanding that distinguishes strong candidates. Mastering the underlying concepts (python) will help you answer variations of this question confidently.

How to Approach This

Start by clearly defining the core concept being asked about. Interviewers want to see that you understand the fundamentals before diving into implementation details. Structure your answer with a definition, then explain the practical application with a concise example. The expert answer includes a code example that demonstrates the implementation pattern.

Expert Answer
467 wordsIncludes code

Python handles exceptions using the try, except, else, and finally blocks. This mechanism is crucial for building robust data pipelines, preventing crashes, and ensuring critical operations like resource cleanup always execute.

Mechanics and Purpose

* try: This block contains the code that might raise an exception.
* except: If an exception occurs within the try block, the corresponding except block (matching the exception type) is executed. You can have multiple except blocks to handle different types of errors specifically.
* else: This optional block executes only if the try block completes successfully without raising any exceptions. It's useful for code that should run exclusively upon successful execution.
* finally: This block guarantees execution regardless of whether an exception occurred, was handled, or even if the try block completed successfully. It is essential for deterministic cleanup operations, such as closing file handles, database connections, or network sockets, preventing resource leaks that can impact scalability and cost in data systems.

Example and Best Practices

Consider a data engineering task involving reading a configuration file.

import logging

logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')

def load_config(filepath):
file_handle = None
try:
file_handle = open(filepath, 'r')
config_data = file_handle.read()
logging.info(f"Configuration loaded successfully from {filepath}")
return config_data
except FileNotFoundError:
logging.error(f"Config file not found: {filepath}. Please ensure it exists.")
raise # Re-raise to signal a critical failure upstream
except IOError as e:
logging.error(f"Error reading config file {filepath}: {e}. Check permissions.")
# Potentially attempt a retry or use a default config here
except Exception as e:
logging.critical(f"An unexpected error occurred loading config {filepath}: {e}")
raise # Catch-all for unknown issues, re-raise as a last resort
finally:
if file_handle:
file_handle.close()
logging.debug(f"Closed file handle for {filepath}")

Key Best Practices:

Specific Exceptions: Always catch specific exception types (e.g., FileNotFoundError, ZeroDivisionError). A bare except: (without specifying an exception type) is dangerous in production as it catches all* exceptions, including KeyboardInterrupt or SystemExit, masking critical issues and preventing graceful shutdowns.
* Logging with Context: Log exceptions with sufficient context (e.g., file path, record ID, stack trace) to aid debugging. Poor logging can mask bugs, leading to corrupted data or resource exhaustion in distributed systems like Spark or Kafka.
* Re-raising: Use raise within an except block to handle an error locally (e.g., log it) but then propagate it up the call stack for higher-level handling or to signal a pipeline failure.
* finally for Cleanup: The finally block is paramount for preventing resource leaks. In data engineering, this ensures database connections, file handles, or Kafka producer/consumer clients are properly closed, even if data processing fails.

In the interview, also mention…

Emphasize how finally is critical for preventing resource leaks in data pipelines, ensuring connections (e.g., to Snowflake, S3, Delta Lake) are closed, even if processing fails midway, which is vital for maintaining system stability and managing cloud costs.

⚡
Pro Tip

Red Flag: Empty except: pass or catching Exception and not re-raising. Pro-Move: 'I catch specific exceptions, log with stack traces, use finally for connection cleanup, and have a top-level handler for unhandled exceptions in long-running services.'

Want all answers as a PDF for offline study?
Seven focused volumes with 750+ in-depth answers — Answer Vault →

Related Python/Coding Questions

easyWhat are traits in Scala, and how are they different from classes?FreemediumWrite a Python function to check if a string is a palindrome.FreeeasyWhat is the difference between a list and a tuple in Python?FreeeasyExplain the difference between shallow copy and deep copy in Python.FreeeasyWrite a Python function to find the first non-repeating character in a string.Free

Level up your prep

Recommended
Educative
Educative Unlimited

800+ hands-on courses — Grokking System Design, Coding Patterns, and AI mock interviews for your DE loop.

Start learning →

Some links below are affiliate links. If you buy through them we may earn a small commission at no extra cost to you — it helps keep DataEngPrep free.

According to DataEngPrep.tech, this is one of the most frequently asked Python/Coding interview questions, reported at 2 companies. DataEngPrep.tech maintains an editor-reviewed database of 1,863 data engineering interview questions across 7 categories.

← Back to all questionsMore Python/Coding questions →
Categories
All QuestionsSQLSpark / Big DataPython / CodingSystem DesignCloud / ToolsBehavioral
By Company
AmazonGoogleDatabricksSnowflakeAWSAzureMicrosoftNetflixUberTCS
Interview Guides
All GuidesTop SQL QuestionsTop Spark QuestionsPySpark QuestionsTop Python QuestionsTop System DesignKafka QuestionsAirflow QuestionsSQL Window FunctionsETL QuestionsData Modeling
Products
AI Interview CoachAnswer AnalyzerSQL PlaygroundResume AnalyzerAnswer Vault PDFsPricing
Company
About & Editorial PolicyContact UsAI DisclosureDisclaimerTerms of ServicePrivacy Policy
© 2026 DataEngPrep.tech. All rights reserved.
AboutBlogContactDisclaimer