Exception Handling and Memory Management - Eli-Coker/2143-OOP-Eli GitHub Wiki

Exception Handling

Exception handling in OOP allows programs to gracefully handle runtime errors instead of crashing. It ensures errors are caught, reported, and resolved in a controlled manner.

  • Try/Except blocks: In Python, surround risky code with try, and handle errors in except
  • Throw Statements: Used to signal an error condition.
  • Custom Exceptions: Define specialized exception classes.

Exception Handling Example in Python:

Memory Management

Memory management ensures efficient allocation, use, and deallocation of resources.

Garbage Allocation

Garbage collection automatically frees memory occupied by unused objects in languages like Python and Java.

Automatic Memory Allocation

  • Automatic memory allocation is handled by the compiler.
  • For example, Stack Memory is automatically allocated and freed.

Automatic Memory Allocation Example in C++:

Manual Memory Allocation

  • Manual memory allocation requires explicit handling with the use of the new and delete keywords.
  • For example, Heap Memory remains allocated until manually freed.

Pointers

  • C++ lacks automatic garbage collection, requiring manual management using pointers:

Manual Memory Allocation using Pointers Example in C++:

Smart Pointers

Smart Pointers provide automatic memory allocation, reducing the risk of memory leaks.

Smart Pointers can be used to solve the following problems:

  • Memory Leaks: Allocated memory that is no longer needed but is not deleted
  • Dangling Pointers: Pointers whose memory is deleted while the pointer is still being used
  • Double Deletion: Two different pointers de-allocating the same memory

Types of Smart Pointers

  • unique_ptr: Sole ownership of an object.
  • shared_ptr: Shared ownership; deallocated when last reference is removed.
  • weak_ptr: Holds a non-owning reference to a shared object.

Smart Pointers Example (using unique_ptr):

References and Resources:

Exception Handling in Python

Memory Management in Python

new and delete Operators in C++

Smart Pointers in C++