Skip to content

Refactor: Replace generic Exception with RuntimeError in Cell.add_agent#2950

Closed
falloficarus22 wants to merge 9 commits intomesa:mainfrom
falloficarus22:change-exception-to-runtimeerror
Closed

Refactor: Replace generic Exception with RuntimeError in Cell.add_agent#2950
falloficarus22 wants to merge 9 commits intomesa:mainfrom
falloficarus22:change-exception-to-runtimeerror

Conversation

@falloficarus22
Copy link
Copy Markdown
Contributor

@falloficarus22 falloficarus22 commented Dec 12, 2025

Description

This PR addresses a FIXME in mesa/discrete_space/cell.py by replacing a generic Exception with a more specific RuntimeError.

Changes

  • Modified Cell.add_agent to raise RuntimeError("Cell is full") instead of Exception("ERROR: Cell is full") when attempting to add an agent to a cell that has reached its capacity.

Motivation:

Using specific exception types allows for better error handling and testing. RuntimeError is semantically more appropriate here as it indicates a state error where the operation cannot be performed due to the current state of the cell (being full).

Summary by CodeRabbit

  • Chores
    • Improved error handling for cell capacity constraints by using more specific exception types.

✏️ Tip: You can customize this high-level summary in your review settings.

@falloficarus22
Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Dec 12, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Dec 12, 2025

Walkthrough

The change replaces a generic Exception with a more specific RuntimeError in the Cell.add_agent method when a cell reaches capacity, improving error specificity without altering function behavior or control flow.

Changes

Cohort / File(s) Summary
Exception Type Refinement
mesa/discrete_space/cell.py
Changed exception type from generic Exception to RuntimeError in Cell.add_agent when cell capacity is exceeded; message remains "Cell is full"

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~2 minutes

  • Single file modification affecting one exception type
  • No logic, control flow, or signature changes
  • Straightforward error handling improvement

Poem

A cell once cried generic despair,
But now speaks with precision so rare—
"RuntimeError!" it says with flair,
When capacity limits fill up its lair. 🐰

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides a clear overview of changes and motivation but does not follow the repository's required PR template structure (bug fix or feature/enhancement templates). Use the appropriate PR template from the repository (bug fix or feature/enhancement) to ensure consistency with repository standards.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and accurately summarizes the main change: replacing a generic Exception with RuntimeError in Cell.add_agent, which directly matches the changeset.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@falloficarus22
Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Dec 12, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@github-actions
Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔵 +0.2% [-0.2%, +0.6%] 🔵 -0.3% [-0.4%, -0.2%]
BoltzmannWealth large 🔵 +0.2% [-0.3%, +0.5%] 🔵 -1.1% [-2.2%, +0.0%]
Schelling small 🔵 -0.2% [-1.2%, +0.8%] 🔵 +0.1% [-0.5%, +0.6%]
Schelling large 🔵 -0.1% [-2.2%, +1.2%] 🔵 +1.5% [+0.5%, +2.8%]
WolfSheep small 🔵 -3.2% [-4.9%, -1.7%] 🔵 +0.8% [+0.6%, +1.0%]
WolfSheep large 🔵 +2.3% [+0.2%, +6.0%] 🔵 +1.4% [+0.6%, +2.1%]
BoidFlockers small 🔵 -0.5% [-1.2%, +0.1%] 🔵 +1.7% [+1.5%, +1.9%]
BoidFlockers large 🔵 -0.4% [-0.8%, +0.1%] 🔵 +0.5% [+0.3%, +0.7%]

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
mesa/discrete_space/cell.py (1)

112-115: Ruff TRY003: consider a domain-specific exception (or adjust rule/config)
Ruff flags Line 113 (TRY003). If this repo follows that rule strictly, define a small custom exception (e.g., CellFullError(RuntimeError)) and raise that (optionally with a default message). Otherwise consider suppressing TRY003 locally for this line if the project doesn’t want bespoke exception types here.

+class CellFullError(RuntimeError):
+    """Raised when adding an agent to a full cell is attempted."""
+    def __init__(self, message: str = "Cell is full") -> None:
+        super().__init__(message)
...
-        if self.capacity and n >= self.capacity:
-            raise RuntimeError("Cell is full")
+        if self.capacity and n >= self.capacity:
+            raise CellFullError()
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a320b79 and 58effcc.

📒 Files selected for processing (1)
  • mesa/discrete_space/cell.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.14.8)
mesa/discrete_space/cell.py

113-113: Avoid specifying long messages outside the exception class

(TRY003)

🔇 Additional comments (1)
mesa/discrete_space/cell.py (1)

112-114: Good specificity upgrade; check downstream expectations for exception type
Switching to RuntimeError is a nice improvement for callers/tests, but it can still be a behavioral break for any code asserting the exact exception type/message (or documenting Exception). Worth a quick scan/update of tests/docs that validate the failure mode of Cell.add_agent.

@quaquel
Copy link
Copy Markdown
Member

quaquel commented Dec 17, 2025

I am not sure using a RuntimeError is the appropriate solution here. One reason for the FIXME was that I am inclined to add a bunch of exceptions to MESA itself.

raise Exception(
"ERROR: Cell is full"
) # FIXME we need MESA errors or a proper error
raise RuntimeError("Cell is full")
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that the type of error isn't the primary concern, but the message. I think something like this would already be far more useful.

Suggested change
raise RuntimeError("Cell is full")
raise Exception(
f"Cannot add agent {agent.unique_id} to cell at {self.coordinate}: "
f"cell is full (capacity: {self.capacity}, current: {n})"
) # FIXME we might want dedicated MESA errors types

@quaquel if we make a Mesa error type, could we use that to (automatically) include some information about:

  • the model state (model.time for example by default)
  • where the error occurred (which agent, model, space, etc.)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure. I tend to keep errors simple with just a message. Including where is not needed because you already have the full stack trace, so you know where it occurred.

@quaquel
Copy link
Copy Markdown
Member

quaquel commented Dec 29, 2025

I have opened a discussion on mesa exceptions in the mesa 4.0 discussion. I am closing this pull request, but I have included a link to it for reference. Depending on how we decide to move forward, we might reopen this or at least draw heavily from it.

@quaquel quaquel closed this Dec 29, 2025
@EwoutH EwoutH mentioned this pull request Jan 14, 2026
42 tasks
@falloficarus22 falloficarus22 deleted the change-exception-to-runtimeerror branch January 15, 2026 15:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants