Course contentsShow
← Java
Lesson 1178 of 2,87027. Queue and Deque ImplementationsFree lesson

Exception-Throwing vs Null-Returning Methods

Understanding add/remove/element (throw exceptions) versus offer/poll/peek (return null on failure).

Exception-Throwing vs Null-Returning Methods

What You'll Learn

You'll learn why the Queue interface provides two versions of each operation—one that throws exceptions and one that returns special values like null—and when to use each.

The Two Flavors of Queue Operations

The Queue interface gives you a choice for every operation:

Operation TypeThrows ExceptionReturns Special Value
Insertadd(e)offer(e)
Removeremove()poll()
Examineelement()peek()

Exception-throwing methods (add, remove, element) fail loudly. If the queue is full, add throws IllegalStateException. If empty, remove and element throw NoSuchElementException.

Null-returning methods (offer, poll, peek) fail silently. offer returns false if insertion fails. poll and peek return null when the queue is empty.

When to Use Which

Think of it like withdrawing money from an ATM:

  • Exception-throwing: "I must get $50 or I want the machine to shout at me!" Use when failure is unexpected and needs immediate attention.
  • Null-returning: "I'll try to get $50, but if it fails, I'll handle it quietly." Use when failure is normal and part of your logic flow.

For bounded queues with capacity limits, offer is preferred over add because "queue full" might be a routine condition. For examining empty queues, peek returning null is cleaner than catching exceptions.

// Exception-throwing: failure is exceptional
queue.add(task); // Throws if full

// Null-returning: failure is expected
if (queue.offer(task)) {
    // Success
} else {
    // Handle full queue gracefully
}

Key Takeaway: Use exception-throwing methods when failure is unexpected and should halt normal flow; use null-returning methods when failure is a routine condition you'll handle explicitly.