Python and R Programming

Exceptions, Logging, Files and Reliable Program Structure

PGCP-BDA

exception hierarchy

Python exceptions derive from BaseException; application errors normally derive from Exception and may be caught by specificity.

Python exceptions are class instances rooted at BaseException; application handlers normally target Exception subclasses from most specific to broader types. Python’s runtime model matters: names refer to objects, operations are dispatched by type and mutability determines whether an operation changes an object or creates another one. Clear code preserves object boundaries, validates external input and uses exceptions to report conditions a caller can handle. A small example of exception hierarchy should be traced from object or input creation through every relevant operation and return value. Include an empty or null-like case and one invalid case so the exception or boundary behavior is visible. Production use should keep external input validation, business logic, storage and presentation in separate functions or classes.

try except else finally

try executes protected code, except handles matching failures, else runs after success and finally runs during normal or exceptional exit.

try executes protected code, except handles matching failures, else runs after success and finally runs during normal or exceptional exit. A concise Python expression is useful only when its data flow remains readable. Choose the built-in type or library abstraction that matches ordering, uniqueness, lookup, numerical or tabular requirements. Observe return values and side effects and keep transformation code separate from input, storage and presentation. When using try except else finally, document which object owns mutable state, which caller releases resources and which failures can propagate. Names and types should express the contract without forcing a reader to inspect every implementation detail. Automated tests should verify the public behavior and avoid depending on incidental internal ordering unless that ordering is part of the contract.

raise

raise starts exception propagation or re-raises the active exception, optionally chaining an explicit cause.

raise starts exception propagation or re-raises the active exception, optionally chaining an explicit cause. The mechanism should be demonstrated with a small valid case, a boundary case and an invalid case. This reveals type conversions, empty inputs, missing values and exception behavior before the same code is placed in an AI data pipeline or web service. The practical value of raise appears when the program changes. A sound design permits one behavior to be replaced or extended without duplicating validation and cleanup code. Logging should identify the operation and outcome without exposing credentials or personal data and concurrent use must be supported explicitly rather than assumed from a successful single-threaded example.

custom exception

A custom exception names a domain-specific failure and should preserve its cause and useful context without exposing secrets.

A Python custom exception subclasses an appropriate Exception type and carries stable domain meaning and safe diagnostic context. Python’s runtime model matters: names refer to objects, operations are dispatched by type and mutability determines whether an operation changes an object or creates another one. Clear code preserves object boundaries, validates external input and uses exceptions to report conditions a caller can handle. A small example of custom exception should be traced from object or input creation through every relevant operation and return value. Include an empty or null-like case and one invalid case so the exception or boundary behavior is visible. Production use should keep external input validation, business logic, storage and presentation in separate functions or classes.

context manager

A context manager defines enter and exit behavior so with can acquire and reliably release a resource around a suite.

A context manager defines enter and exit behavior so with can acquire and reliably release a resource around a suite. A concise Python expression is useful only when its data flow remains readable. Choose the built-in type or library abstraction that matches ordering, uniqueness, lookup, numerical or tabular requirements. Observe return values and side effects and keep transformation code separate from input, storage and presentation. When using context manager, document which object owns mutable state, which caller releases resources and which failures can propagate. Names and types should express the contract without forcing a reader to inspect every implementation detail. Automated tests should verify the public behavior and avoid depending on incidental internal ordering unless that ordering is part of the contract.

logging levels

Logging levels order diagnostic severity from debug and info through warning, error and critical for filtering and routing.

Logging levels order diagnostic severity from debug and info through warning, error and critical for filtering and routing. A concise Python expression is useful only when its data flow remains readable. Choose the built-in type or library abstraction that matches ordering, uniqueness, lookup, numerical or tabular requirements. Observe return values and side effects and keep transformation code separate from input, storage and presentation. When using logging levels, document which object owns mutable state, which caller releases resources and which failures can propagate. Names and types should express the contract without forcing a reader to inspect every implementation detail. Automated tests should verify the public behavior and avoid depending on incidental internal ordering unless that ordering is part of the contract.

structured logs

Structured logs store named fields such as event, request ID, duration and outcome so machines can query them reliably.

Structured logs store named fields such as event, request ID, duration and outcome so machines can query them reliably. The mechanism should be demonstrated with a small valid case, a boundary case and an invalid case. This reveals type conversions, empty inputs, missing values and exception behavior before the same code is placed in an AI data pipeline or web service. The practical value of structured logs appears when the program changes. A sound design permits one behavior to be replaced or extended without duplicating validation and cleanup code. Logging should identify the operation and outcome without exposing credentials or personal data and concurrent use must be supported explicitly rather than assumed from a successful single-threaded example.

text and binary files

Text mode decodes bytes into strings using an encoding; binary mode reads and writes bytes unchanged.

with statement

The with statement enters a context manager and guarantees its exit method runs when the block ends, including during exception propagation.

reliable program structure

A design with validated inputs, focused functions, explicit errors, deterministic cleanup, logging and a clear entry point.

Debugging

Debugging reproduces a failure, observes state and control flow, narrows the cause, applies a focused correction and verifies regression behavior. The mechanism should be demonstrated with a small valid case, a boundary case and an invalid case. This reveals type conversions, empty inputs, missing values and exception behavior before the same code is placed in an AI data pipeline or web service. The practical value of debugging appears when the program changes. A sound design permits one behavior to be replaced or extended without duplicating validation and cleanup code. Logging should identify the operation and outcome without exposing credentials or personal data and concurrent use must be supported explicitly rather than assumed from a successful single-threaded example.

Assertion

assert checks an internal invariant during development and can be disabled, so it must not validate untrusted external input. Python’s runtime model matters: names refer to objects, operations are dispatched by type and mutability determines whether an operation changes an object or creates another one. Clear code preserves object boundaries, validates external input and uses exceptions to report conditions a caller can handle. A small example of assertion should be traced from object or input creation through every relevant operation and return value. Include an empty or null-like case and one invalid case so the exception or boundary behavior is visible. Production use should keep external input validation, business logic, storage and presentation in separate functions or classes.

Continue learning

Related notes

Put this topic into timed practice

Open mock tests when you want full-exam pacing, or keep drilling in practice mode.