Exception handling is one of the core pillars of application development as it helps us to catch errors and perform a suitable action for it. Use the Below detailed cheat sheet on Python Exception handling to quickly revise the topic before the interview.

Python Exceptions Handling Cheatsheet

What Exceptions Mean

Runtime errors that change the normal flow of a program

Exception Example

    x = 10 / 0
    # ZeroDivisionError

    Basic try-except Structure

      try:
          risky_code()
      except ExceptionType:
          handle_error()

      Complete try-except Syntax

        try:
            code
        except ExceptionType1:
            handler1
        except ExceptionType2 as e:
            handler2
        else:
            runs_if_no_exception
        finally:
            always_runs

        Execution Flow

        • try block executes
        • If exception occurs then we go to matching except
        • If no exception - else
        • finally always executes

        Built-in Exception Hierarchy

        • BaseException
        • Exception
        • ValueError
        • TypeError
        • IndexError
        • KeyError
        • RuntimeError
        • ImportError
        • FileNotFoundError
        • ZeroDivisionError
        • KeyboardInterrupt
        • SystemExit

        Interview Advice

        Avoid catching BaseException as it will prevent SystemExit and KeyboardInterrupt.

        Common Types of Exceptions

        • ValueError — Wrong value, correct type
        • TypeError — Wrong type
        • KeyError — Missing dictionary key
        • IndexError — Out-of-range index
        • ZeroDivisionError — Division by zero

        Common Exception Examples

          int('abc')
          '5' + 3
          row['age']
          arr[100]
          loss / 0

          Catch Specific Exception

            try:
                value = int(x)
            except ValueError:
                value = None

            Catch Multiple Exceptions

              try:
                  process(data)
              except (ValueError, TypeError):
                  log_error()

              Generic Catch

                except Exception as e:
                    print(e)

                Production Rule

                When you deploy a website in production, never silently pass exceptions.

                else Block

                  try:
                      result = compute()
                  except ValueError:
                      handle_error()
                  else:
                      save(result)

                  finally Block

                    try:
                        f = open('data.csv')
                        process(f)
                    finally:
                        f.close()

                    Interview Insight

                    finally executes even if you return or raise.

                    Raising Exceptions

                      if df.empty:
                          raise ValueError('DataFrame is empty')

                      Raise with Custom Message

                        raise RuntimeError('Training failed')

                        Re-raise Exception

                          try:
                              risky()
                          except Exception:
                              log()
                              raise

                          Why Custom Exceptions

                          • Cleaner pipelines
                          • Domain-specific errors
                          • Better debugging

                          Define Custom Exception

                            class DataValidationError(Exception):
                                pass

                            Use Custom Exception

                              if missing_rate > 0.3:
                                  raise DataValidationError('Too much missing data')

                              Interview Question

                              Why subclass Exception and not BaseException?

                              Advanced Exception Handling Patterns

                              Exception Chaining (Preserve Original Error)

                                try:
                                    load_data()
                                except FileNotFoundError as e:
                                    raise RuntimeError('Pipeline failed') from e

                                Without Exception Chaining (Bad)

                                  raise RuntimeError('Failed')

                                  Interview Tip

                                  Use from e for debuggability.

                                  Assertions vs Exceptions

                                  • Assertion — used for developer checks
                                  • Can be disabled with -O flag
                                  • Exception — used for user or data errors

                                  Assertion Example

                                    assert x > 0

                                    Exception Example

                                      if x <= 0:
                                          raise ValueError('x must be positive')

                                      Rule

                                      • Assertions — internal invariants
                                      • Exceptions — user or data errors

                                      Exception Handling in Data Science Pipelines

                                      • Data validation
                                      • Model training guards
                                      • ETL pipeline error handling

                                      Data Validation Example

                                        def validate(df):
                                            if df.isnull().mean().max() > 0.2:
                                                raise ValueError('Too many nulls')

                                        Model Training Guard

                                          try:
                                              model.fit(X, y)
                                          except ValueError as e:
                                              log_metrics('training_failed')
                                              raise

                                          ETL Pipeline Pattern

                                            try:
                                                extract()
                                                transform()
                                                load()
                                            except Exception:
                                                rollback()
                                                raise

                                            Anti-Patterns

                                            • Bare except
                                            • Swallowing errors
                                            • Using exceptions for flow control

                                            Bare Except (Bad)

                                              except:
                                                  pass

                                              Swallowing Errors (Bad)

                                                except Exception:
                                                    return None

                                                Exceptions for Flow Control (Bad)

                                                  try:
                                                      return d[key]
                                                  except KeyError:
                                                      return None

                                                  Better Alternative

                                                    d.get(key)

                                                    Logging Exceptions

                                                      import logging
                                                      
                                                      try:
                                                          risky()
                                                      except Exception:
                                                          logging.exception('Pipeline crashed')

                                                      Why logging.exception?

                                                      • Automatically logs stack trace
                                                      • Essential for production ML systems

                                                      Advanced Topics

                                                      • Partial failure handling in loops
                                                      • Context managers

                                                      try in Loops (Partial Failure Handling)

                                                        results = []
                                                        
                                                        for row in data:
                                                            try:
                                                                results.append(process(row))
                                                            except ValueError:
                                                                continue

                                                        Context Managers (with)

                                                          with open('data.csv') as f:
                                                              process(f)

                                                          Equivalent try-finally

                                                            try:
                                                                f = open(...)
                                                            finally:
                                                                f.close()

                                                            Exception Handling – Interview Cheat Q&A

                                                            Interview Cheat Q&A

                                                            • Q: Difference between raise and raise e?
                                                            • raise — preserves original traceback
                                                            • raise e — resets traceback

                                                            When NOT to Catch Exceptions?

                                                            • At low-level utility functions
                                                            • Let higher-level code decide

                                                            Best Practice Summary

                                                            • Catch specific exceptions
                                                            • Add context when re-raising
                                                            • Log before failing
                                                            • Never hide errors

                                                            Interview Question 1: Safe Integer Parse

                                                              def safe_int(s, default=None):
                                                                  try:
                                                                      return int(s)
                                                                  except (TypeError, ValueError):
                                                                      return default

                                                              Interview Question 2: Safe Dict Lookup with Required Keys

                                                                def get_required(d, key):
                                                                    try:
                                                                        return d[key]
                                                                    except KeyError as e:
                                                                        raise KeyError(f"Missing required key: {key}") from e

                                                                Interview Question 3: Divide with Validation and Custom Exception

                                                                  class InvalidDenominatorError(Exception):
                                                                      pass
                                                                  
                                                                  def divide(a, b):
                                                                      if b == 0:
                                                                          raise InvalidDenominatorError("Denominator cannot be zero")
                                                                      return a / b

                                                                  Interview Question 4: Robust Mean for Messy Lists

                                                                    def robust_mean(xs):
                                                                        total = 0.0
                                                                        count = 0
                                                                        for x in xs:
                                                                            try:
                                                                                if x is None:
                                                                                    raise TypeError("None is not numeric")
                                                                                total += float(x)
                                                                                count += 1
                                                                            except (TypeError, ValueError):
                                                                                continue
                                                                        if count == 0:
                                                                            raise ValueError("No valid numeric values found")
                                                                        return total / count

                                                                    Interview Question 5: Read a Text File Safely

                                                                      def read_text(path):
                                                                          try:
                                                                              with open(path, "r", encoding="utf-8") as f:
                                                                                  return f.read()
                                                                          except FileNotFoundError as e:
                                                                              raise FileNotFoundError(f"File not found: {path}") from e

                                                                      Interview Question 6: Retry Wrapper

                                                                        def retry(fn, tries, exceptions=(Exception,)):
                                                                            last_exc = None
                                                                            for _ in range(tries):
                                                                                try:
                                                                                    return fn()
                                                                                except exceptions as e:
                                                                                    last_exc = e
                                                                            raise last_exc

                                                                        Interview Question 7: Context Manager that Converts Exceptions

                                                                          from contextlib import contextmanager
                                                                          
                                                                          @contextmanager
                                                                          def suppress_and_return(default):
                                                                              out = []
                                                                              try:
                                                                                  yield out
                                                                              except (ValueError, TypeError):
                                                                                  out.append(default)

                                                                          Interview Question 8: Validate Dataset Schema

                                                                            class DataValidationError(Exception):
                                                                                pass
                                                                            
                                                                            def validate_rows(rows, required_keys):
                                                                                req = set(required_keys)
                                                                                for i, row in enumerate(rows):
                                                                                    if not isinstance(row, dict):
                                                                                        raise DataValidationError(f"Row {i} is not a dict")
                                                                                    missing = req - set(row.keys())
                                                                                    if missing:
                                                                                        raise DataValidationError(f"Row {i} missing keys: {sorted(missing)}")
                                                                                return True

                                                                            Interview Question 9: Exception Chaining in Parsing Pipeline

                                                                              def parse_then_scale(s, factor):
                                                                                  try:
                                                                                      x = float(s)
                                                                                  except (TypeError, ValueError) as e:
                                                                                      raise ValueError("Bad numeric input") from e
                                                                                  return x * factor

                                                                              Interview Question 10: Ensure Cleanup with finally

                                                                                def process_with_cleanup(resource):
                                                                                    resource.open()
                                                                                    try:
                                                                                        return resource.read()
                                                                                    finally:
                                                                                        resource.close()