Skip to content

fix: replace 42 bare excepts with except Exception#180

Closed
haosenwang1018 wants to merge 1 commit intosimular-ai:mainfrom
haosenwang1018:fix/bare-excepts
Closed

fix: replace 42 bare excepts with except Exception#180
haosenwang1018 wants to merge 1 commit intosimular-ai:mainfrom
haosenwang1018:fix/bare-excepts

Conversation

@haosenwang1018
Copy link
Copy Markdown

@haosenwang1018 haosenwang1018 commented Feb 25, 2026

Replace 42 bare except: with except Exception: across 23 files. Bare except: catches KeyboardInterrupt and SystemExit, masking real errors and preventing clean process termination.

Summary by CodeRabbit

  • Refactor
    • Improved exception handling throughout the codebase by replacing generic error-catching with more specific exception types, enhancing code robustness and error handling clarity without changing user-facing functionality or behavior.

Bare except catches KeyboardInterrupt and SystemExit, masking real errors.
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Feb 25, 2026

📝 Walkthrough

Walkthrough

Systematic replacement of bare except: clauses with explicit except Exception: across multiple modules spanning agent implementations, CLI utilities, knowledge management, and setup scripts. This narrows exception handling scope to standard Exceptions while allowing system-exiting exceptions to propagate.

Changes

Cohort / File(s) Summary
Agent Core Modules
gui_agents/s1/core/AgentS.py, gui_agents/s2/agents/agent_s.py
Replaced bare except with except Exception in update_narrative_memory and update_episodic_memory methods for memory file loading operations.
Knowledge Management
gui_agents/s1/core/Knowledge.py, gui_agents/s2/core/knowledge.py
Narrowed exception handling from bare except to except Exception in query formulation, search operations, and memory save methods. Preserves fallback behavior with empty dicts on IO failures.
Linux/macOS/Windows ACI Modules
gui_agents/s1/aci/LinuxOSACI.py, gui_agents/s1/aci/MacOSACI.py, gui_agents/s1/aci/WindowsOSACI.py
Replaced bare except with except Exception in find_element, type, scroll, and node creation methods across platform-specific accessibility implementations.
Grounding Agents
gui_agents/s1/aci/windowsagentarena/GroundingAgent.py, gui_agents/s2/agents/grounding.py, gui_agents/s2_5/agents/grounding.py, gui_agents/s3/agents/grounding.py
Narrowed exception handling in set_cell_values and element access methods from bare except to except Exception, preserving ValueError raises and fallback behavior.
CLI Applications
gui_agents/s1/cli_app.py, gui_agents/s2/cli_app.py, gui_agents/s2_5/cli_app.py, gui_agents/s3/cli_app.py
Tightened get_char exception handling from bare except to except Exception while retaining fallback to input() for non-terminal environments.
Comparative Judge Utility
gui_agents/s3/bbon/comparative_judge.py
Narrowed exception handling in get_final_screenshot_file from bare except to except Exception, preserving fallback return of 0.
OSWorld Setup - Standard Runs
osworld_setup/s1/run.py, osworld_setup/s2/run.py, osworld_setup/s3/run.py
Replaced bare except with except Exception in get_result for file reading and float conversion operations, maintaining 0.0 append on error.
OSWorld Setup - Local Runs
osworld_setup/s2_5/run_local.py, osworld_setup/s3/run_local.py
Tightened exception handling in get_result from bare except to except Exception for result file processing.
OSWorld Setup - Fact Generation
osworld_setup/s3/bbon/generate_facts.py
Replaced bare except blocks with except Exception in three locations: JSON trajectory parsing, step number extraction, and trajectory data loading operations.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

Possibly related PRs

  • S3 🧠🤓🤯 #142: Related code path in gui_agents/s3/bbon/comparative_judge.py get_final_screenshot_file exception handling; this PR tightens bare except to explicit Exception handling matching the same pattern.

Poem

🐰 Bare excepts be gone, hooray! /\
Explicit Exception saves the day,
System exits now roam free,
Cleaner code for all to see! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 67.74% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: replacing 42 bare except clauses with except Exception across multiple files. It is concise, directly matches the changeset, and provides meaningful context about the primary refactoring.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 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.

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: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
osworld_setup/s1/run.py (1)

224-228: ⚠️ Potential issue | 🟡 Minor

Unconditional env.controller.end_recording() may raise AttributeError if the provider has no controller.

The s3 counterpart (osworld_setup/s3/run_local.py, lines 287–290) guards this call with if hasattr(env, "controller") and env.controller is not None. This file does not, so any non-VMware provider that lacks a controller attribute will raise an AttributeError inside the except handler itself, masking the original error.

This is a pre-existing issue, but now that the surrounding handler is explicitly narrowed it is more visible.

🛡️ Proposed fix
-            env.controller.end_recording(
-                os.path.join(example_result_dir, "recording.mp4")
-            )
+            if hasattr(env, "controller") and env.controller is not None:
+                env.controller.end_recording(
+                    os.path.join(example_result_dir, "recording.mp4")
+                )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@osworld_setup/s1/run.py` around lines 224 - 228, The except block logs the
error and then unconditionally calls env.controller.end_recording(...), which
can raise AttributeError if env has no controller; update the handler in run.py
to check hasattr(env, "controller") and env.controller is not None before
calling env.controller.end_recording with os.path.join(example_result_dir,
"recording.mp4") so the cleanup is only attempted when a controller exists (use
the same guard approach as in osworld_setup/s3/run_local.py).
osworld_setup/s3/bbon/generate_facts.py (1)

28-35: ⚠️ Potential issue | 🟡 Minor

Silent except Exception: pass on JSON parse discards the actual error.

When json.loads fails, the real error (e.g., json.JSONDecodeError) is swallowed and replaced by the generic ValueError on line 35. A caller seeing "No pyautogui action found for step N" has no way to distinguish a malformed line from a genuinely missing action. Consider logging the parse error, and narrowing the catch to json.JSONDecodeError.

🔧 Proposed fix
         try:
             data = json.loads(trajectory_lines[i])
             pyautogui_action = data.get("exec_code")
-        except Exception:
-            pass
+        except json.JSONDecodeError as e:
+            print(f"Warning: could not parse trajectory line {i}: {e}")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@osworld_setup/s3/bbon/generate_facts.py` around lines 28 - 35, The try/except
currently swallows all errors when parsing trajectory_lines[i]; narrow the
except to catch json.JSONDecodeError (not Exception), capture the exception as
e, and log the parse failure including the index i and the offending line
(trajectory_lines[i]) and the error message (e) before continuing; keep the
existing behavior that later raises ValueError if pyautogui_action is None.
Ensure you import or use the module logger (e.g., logging) and reference the
variables and context names shown (trajectory_lines, pyautogui_action, i) so the
log makes it clear this was a JSON parse error rather than a missing exec_code.
🧹 Nitpick comments (16)
gui_agents/s1/cli_app.py (1)

42-43: except Exception is correct but still broader than necessary.

The only realistically expected failures inside get_char are:

  • ImportError — when termios/tty or msvcrt are unavailable
  • io.UnsupportedOperation / OSError — when stdin.fileno() or termios operations fail in a non-terminal environment

Narrowing the catch avoids silently swallowing unexpected errors (e.g., a MemoryError or a logic bug in a future edit):

♻️ Proposed narrowing
-    except Exception:
+    except (ImportError, OSError):
         return input()  # Fallback for non-terminal environments
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@gui_agents/s1/cli_app.py` around lines 42 - 43, The except block in get_char
is too broad; narrow it to only the expected exceptions by catching ImportError,
io.UnsupportedOperation and OSError (the ones raised when termios/tty or
stdin.fileno()/termios fail) instead of Exception, and ensure io is imported so
io.UnsupportedOperation is available; keep the existing fallback return input()
for non-terminal environments.
osworld_setup/s3/run_local.py (1)

356-365: Narrow to (OSError, ValueError) in get_result.

float(open(...).read()) raises only OSError (I/O failure) or ValueError (non-numeric content). Using except Exception hides any other unexpected errors silently.

♻️ Proposed narrowing
-                        except Exception:
+                        except (OSError, ValueError):
                             all_result.append(0.0)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@osworld_setup/s3/run_local.py` around lines 356 - 365, The try/except in
get_result currently swallows all exceptions; narrow it to only catch I/O and
parse errors by replacing the broad "except Exception" with "except (OSError,
ValueError)" around the float(open(...).read()) read/parse block (and keep
appending 0.0 on those specific failures) so other unexpected exceptions
propagate; reference the get_result logic that builds all_result and the
float(open(os.path.join(example_path, "result.txt"), "r").read()) call when
making the change.
gui_agents/s3/bbon/comparative_judge.py (1)

21-25: Narrow to the two expected exception types in extract_step_num.

Only IndexError (insufficient split parts) or ValueError (int() on non-numeric content) can realistically occur here:

♻️ Proposed narrowing
     def extract_step_num(filename):
         try:
             return int(filename.split("_")[1].split(".")[0])
-        except Exception:
+        except (IndexError, ValueError):
             return 0
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@gui_agents/s3/bbon/comparative_judge.py` around lines 21 - 25, The function
extract_step_num currently catches all exceptions; narrow the exception handling
to only the expected types by catching IndexError and ValueError explicitly
(i.e., replace except Exception with except (IndexError, ValueError)) so only
parsing/split errors return 0 and other unexpected exceptions bubble up.
gui_agents/s3/cli_app.py (1)

45-46: Same get_char narrowing opportunity as gui_agents/s1/cli_app.py.

Prefer except (ImportError, OSError): for the same reasons noted there.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@gui_agents/s3/cli_app.py` around lines 45 - 46, Update the broad except in
get_char to only catch the expected import/terminal failures: replace "except
Exception:" with "except (ImportError, OSError):" (or the same tuple used in
gui_agents/s1/cli_app.py) so only import/OS-level terminal issues fall back to
input(); keep the existing fallback return input() and ensure the change
references get_char to locate the handler.
gui_agents/s2/cli_app.py (1)

44-45: Same get_char narrowing opportunity as gui_agents/s1/cli_app.py.

Prefer except (ImportError, OSError): for the same reasons noted there.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@gui_agents/s2/cli_app.py` around lines 44 - 45, In the get_char function
replace the broad "except Exception:" fallback with a narrowed except clause
"except (ImportError, OSError):" so only import/OS-related failures fall back to
input(); update the except block that currently returns input() to use these two
specific exceptions (refer to the get_char function and its fallback except
block).
gui_agents/s2_5/cli_app.py (1)

44-45: Same get_char narrowing opportunity as gui_agents/s1/cli_app.py.

Prefer except (ImportError, OSError): for the same reasons noted there.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@gui_agents/s2_5/cli_app.py` around lines 44 - 45, The except block in
get_char (cli_app.py) is too broad; narrow the exception handling to only
ImportError and OSError (i.e., use except (ImportError, OSError):) so we catch
the expected module/load errors while letting other exceptions surface, and keep
the same fallback return input() behavior inside that narrowed handler.
osworld_setup/s1/run.py (1)

294-303: Narrow to (OSError, ValueError) in get_result.

Same as osworld_setup/s3/run_local.py — only OSError or ValueError are expected from float(open(...).read()).

♻️ Proposed narrowing
-                        except Exception:
+                        except (OSError, ValueError):
                             all_result.append(0.0)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@osworld_setup/s1/run.py` around lines 294 - 303, The broad except Exception
in get_result should be narrowed to only catch the expected errors: replace the
generic except with except (OSError, ValueError) around the
float(open(os.path.join(example_path, "result.txt"), "r").read()) call so only
file/IO and conversion errors are swallowed; keep appending 0.0 to all_result
for those cases and leave other exceptions to surface. Use the existing
all_result and example_path variables and the get_result function context when
making this change.
osworld_setup/s3/run.py (1)

515-524: Narrow to (OSError, ValueError) in get_result.

Same as the other run.py variants — only OSError or ValueError are expected here.

♻️ Proposed narrowing
-                        except Exception:
+                        except (OSError, ValueError):
                             all_result.append(0.0)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@osworld_setup/s3/run.py` around lines 515 - 524, The except clause in
get_result currently catches all exceptions; narrow it to only catch OSError and
ValueError (the expected errors when opening/reading/parsing result.txt) and
leave other exceptions to surface; locate the try/except around reading
os.path.join(example_path, "result.txt") which appends to all_result and replace
"except Exception" with "except (OSError, ValueError)" so only file I/O and
float conversion errors are handled.
gui_agents/s2/core/knowledge.py (2)

88-93: Prefer targeted read exceptions over blanket Exception in cache loads.

These handlers still swallow unexpected runtime bugs and silently coerce to {}. Restrict to expected file/JSON failures and let unexpected exceptions surface.

Proposed refactor
-        except Exception:
+        except (FileNotFoundError, json.JSONDecodeError, OSError):
             formulate_query = {}
-        except Exception:
+        except (FileNotFoundError, json.JSONDecodeError, OSError):
             exist_search_results = {}

Also applies to: 129-133

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@gui_agents/s2/core/knowledge.py` around lines 88 - 93, Replace the blanket
"except Exception" in the cache load blocks so only expected I/O/parse errors
are swallowed: catch FileNotFoundError and json.JSONDecodeError (and optionally
PermissionError) around the open/json.load in the block that assigns
formulate_query (and the similar block around the other cache load at lines
129-133), set formulate_query = {} on those specific exceptions, and let all
other exceptions propagate so unexpected runtime bugs are not silently ignored.

272-275: Avoid silent KB reset on unexpected load failures before persisting.

Defaulting to {} for any exception can lead to unintended overwrite behavior in subsequent writes. Keep fallback only for expected read/parsing failures.

Also applies to: 297-300

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@gui_agents/s2/core/knowledge.py` around lines 272 - 275, The current
try/except around load_knowledge_base(self.episodic_memory_path) silently
swallows all exceptions and defaults kb to {}, which can cause unintended
overwrites on subsequent writes; update the block so it only catches expected
read/parsing errors (e.g., FileNotFoundError, JSONDecodeError or whatever
load_knowledge_base raises for missing/corrupt data) and falls back to {} in
those cases, but re-raises or propagates any other unexpected exceptions so they
aren’t hidden. Apply the same change to the analogous block later (around lines
handling the second load) and reference the load_knowledge_base call and
self.episodic_memory_path when making the change.
gui_agents/s1/core/Knowledge.py (1)

82-86: Use targeted exceptions for JSON/cache reads.

Catching Exception here still suppresses non-I/O defects. Prefer handling FileNotFoundError/json.JSONDecodeError/OSError explicitly.

Also applies to: 123-127

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@gui_agents/s1/core/Knowledge.py` around lines 82 - 86, Replace the broad
except Exception in the JSON/cache read blocks (the try that loads
formulate_query from query_path and the similar block around lines 123-127) with
targeted exception handling: catch FileNotFoundError, json.JSONDecodeError, and
OSError and set formulate_query = {} (or the equivalent fallback) in those
cases, and re-raise any other unexpected exceptions so non-I/O bugs aren’t
silently swallowed; reference the variables/query_path and the formulate_query
load logic to locate both spots to update.
gui_agents/s1/aci/MacOSACI.py (1)

308-312: Narrow fallback catches around find_element to expected input/index errors.

except Exception can hide unrelated bugs and silently route actions to fallback targets. Catch concrete exceptions (TypeError, ValueError, IndexError) instead.

Also applies to: 403-406

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@gui_agents/s1/aci/MacOSACI.py` around lines 308 - 312, The current broad
except Exception around the call to self.find_element(element_id) (which sets
node) should be narrowed to only catch the expected input/index errors; update
the try/except blocks in MacOSACI.py around the find_element usage (both the
block where node = self.find_element(element_id) and the similar block at the
later occurrence) to catch TypeError, ValueError, and IndexError instead of
Exception, leaving other exceptions to propagate; ensure the except sets node =
None as before and keep the original behavior for valid errors.
gui_agents/s2/agents/agent_s.py (1)

349-353: Tighten memory-file read error handling in update paths.

Please catch expected JSON/file exceptions only; except Exception here can hide unexpected bugs and silently reset loaded state to {}.

Safer pattern
-            try:
-                reflections = json.load(open(reflection_path))
-            except Exception:
+            try:
+                with open(reflection_path, "r", encoding="utf-8") as f:
+                    reflections = json.load(f)
+            except (FileNotFoundError, json.JSONDecodeError, OSError):
                 reflections = {}

Also applies to: 385-391

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@gui_agents/s2/agents/agent_s.py` around lines 349 - 353, Replace the broad
except Exception around json.load(open(reflection_path)) with targeted error
handling: open the file using a context manager (with open(reflection_path, "r")
as f) and call json.load(f), and catch only expected exceptions such as
json.JSONDecodeError, FileNotFoundError, and OSError/PermissionError to set
reflections = {} (and optionally log a warning); let all other exceptions
propagate so unexpected bugs are not silenced. Apply the same change to the
other occurrence around lines 385-391 that uses reflection_path.
gui_agents/s1/aci/windowsagentarena/GroundingAgent.py (1)

307-314: Avoid catch-all fallbacks in action-selection paths.

Using except Exception here can mask state bugs and unintentionally act on element 0. Catch only expected conversion/index failures.

Also applies to: 375-379, 548-551

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@gui_agents/s1/aci/windowsagentarena/GroundingAgent.py` around lines 307 -
314, The find_element method currently swallows all Exceptions and falls back to
self.nodes[0]; replace the broad except with targeted exception handling for
ValueError (int conversion) and IndexError (out-of-range) so you don't mask
other bugs: parse element_id with int inside a try and except (ValueError,
IndexError) only, log or set self.index_out_of_range_flag and return None (or
raise a specific error) instead of defaulting to nodes[0]; apply the same change
to the other action-selection sites mentioned (the similar blocks at lines
corresponding to the other occurrences) by replacing except Exception with
except (ValueError, IndexError) and removing the implicit fallback to index 0.
gui_agents/s1/aci/LinuxOSACI.py (1)

414-418: Outer try/except Exception in type() and scroll() is redundant.

find_element() (lines 344–351) already catches IndexError internally and never re-raises it. The outer except Exception here will only fire for genuinely unexpected errors (e.g., AttributeError on self.nodes), which is unlikely and unrelated to the stated intent. Consider removing the outer guard or, if intentional, add a comment explaining what it catches.

Also applies to: 517-520

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@gui_agents/s1/aci/LinuxOSACI.py` around lines 414 - 418, Remove the redundant
outer try/except around the call to find_element in the type() method (and the
analogous block in scroll()); instead directly assign node =
self.find_element(element_id) if element_id is not None else None because
find_element already handles IndexError internally—if you actually intend to
catch other unexpected errors, replace the broad except with a specific
exception or add an inline comment in type() and scroll() explaining which
non-IndexError cases you want to guard against.
gui_agents/s1/aci/WindowsOSACI.py (1)

303-306: Outer try/except Exception wrapping find_element() is redundant in both type() and scroll().

WindowsACI.find_element() (lines 228–233) already catches IndexError internally and returns self.nodes[0]. The outer except Exception here only fires for errors unrelated to the index bounds (e.g., self.nodes being uninitialized), which are separate, unexpected failures better left to propagate. This mirrors the same pattern flagged in LinuxOSACI.

Also applies to: 387-390

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@gui_agents/s1/aci/WindowsOSACI.py` around lines 303 - 306, The outer
try/except that wraps calls to self.find_element() in WindowsACI.type() and
WindowsACI.scroll() is redundant and suppresses unexpected errors; remove the
surrounding try/except blocks so that WindowsACI.find_element() (which already
handles IndexError) returns normally or lets other exceptions
propagate—specifically, eliminate the try/except around the node =
self.find_element(element_id) if element_id is not None else None lines in both
type() and scroll() so only intentional IndexError handling stays inside
find_element().
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@gui_agents/s1/aci/LinuxOSACI.py`:
- Around line 670-673: The try/except around calling attr_func() that sets
attribute_dict[f"{value_key}{attr_name}"] currently swallows all exceptions;
change the except to log the exception at debug level instead of passing so
failures are observable. Specifically, inside the except Exception block in
LinuxOSACI.py where attribute_dict, value_key, attr_name, and attr_func are
used, call the module’s logger (or create one if missing) to emit a debug log
with a clear message including the attribute key and the caught exception
information (e.g., exception text/traceback) and then continue preserving the
current behavior (do not re-raise).

In `@osworld_setup/s3/bbon/generate_facts.py`:
- Around line 90-94: Replace the silent catch around opening/reading
trajectory_file with a narrow OSError handler: attempt the with
open(trajectory_file, "r") as f: trajectory_lines = f.readlines() block, and on
failure catch except OSError as e: set trajectory_lines = [] (or ensure it
remains defined) and log the error including trajectory_file and e (use the
module/logger variable you have), rather than using a bare except Exception:
pass, so permission/IO errors are surfaced for debugging.

---

Outside diff comments:
In `@osworld_setup/s1/run.py`:
- Around line 224-228: The except block logs the error and then unconditionally
calls env.controller.end_recording(...), which can raise AttributeError if env
has no controller; update the handler in run.py to check hasattr(env,
"controller") and env.controller is not None before calling
env.controller.end_recording with os.path.join(example_result_dir,
"recording.mp4") so the cleanup is only attempted when a controller exists (use
the same guard approach as in osworld_setup/s3/run_local.py).

In `@osworld_setup/s3/bbon/generate_facts.py`:
- Around line 28-35: The try/except currently swallows all errors when parsing
trajectory_lines[i]; narrow the except to catch json.JSONDecodeError (not
Exception), capture the exception as e, and log the parse failure including the
index i and the offending line (trajectory_lines[i]) and the error message (e)
before continuing; keep the existing behavior that later raises ValueError if
pyautogui_action is None. Ensure you import or use the module logger (e.g.,
logging) and reference the variables and context names shown (trajectory_lines,
pyautogui_action, i) so the log makes it clear this was a JSON parse error
rather than a missing exec_code.

---

Nitpick comments:
In `@gui_agents/s1/aci/LinuxOSACI.py`:
- Around line 414-418: Remove the redundant outer try/except around the call to
find_element in the type() method (and the analogous block in scroll()); instead
directly assign node = self.find_element(element_id) if element_id is not None
else None because find_element already handles IndexError internally—if you
actually intend to catch other unexpected errors, replace the broad except with
a specific exception or add an inline comment in type() and scroll() explaining
which non-IndexError cases you want to guard against.

In `@gui_agents/s1/aci/MacOSACI.py`:
- Around line 308-312: The current broad except Exception around the call to
self.find_element(element_id) (which sets node) should be narrowed to only catch
the expected input/index errors; update the try/except blocks in MacOSACI.py
around the find_element usage (both the block where node =
self.find_element(element_id) and the similar block at the later occurrence) to
catch TypeError, ValueError, and IndexError instead of Exception, leaving other
exceptions to propagate; ensure the except sets node = None as before and keep
the original behavior for valid errors.

In `@gui_agents/s1/aci/windowsagentarena/GroundingAgent.py`:
- Around line 307-314: The find_element method currently swallows all Exceptions
and falls back to self.nodes[0]; replace the broad except with targeted
exception handling for ValueError (int conversion) and IndexError (out-of-range)
so you don't mask other bugs: parse element_id with int inside a try and except
(ValueError, IndexError) only, log or set self.index_out_of_range_flag and
return None (or raise a specific error) instead of defaulting to nodes[0]; apply
the same change to the other action-selection sites mentioned (the similar
blocks at lines corresponding to the other occurrences) by replacing except
Exception with except (ValueError, IndexError) and removing the implicit
fallback to index 0.

In `@gui_agents/s1/aci/WindowsOSACI.py`:
- Around line 303-306: The outer try/except that wraps calls to
self.find_element() in WindowsACI.type() and WindowsACI.scroll() is redundant
and suppresses unexpected errors; remove the surrounding try/except blocks so
that WindowsACI.find_element() (which already handles IndexError) returns
normally or lets other exceptions propagate—specifically, eliminate the
try/except around the node = self.find_element(element_id) if element_id is not
None else None lines in both type() and scroll() so only intentional IndexError
handling stays inside find_element().

In `@gui_agents/s1/cli_app.py`:
- Around line 42-43: The except block in get_char is too broad; narrow it to
only the expected exceptions by catching ImportError, io.UnsupportedOperation
and OSError (the ones raised when termios/tty or stdin.fileno()/termios fail)
instead of Exception, and ensure io is imported so io.UnsupportedOperation is
available; keep the existing fallback return input() for non-terminal
environments.

In `@gui_agents/s1/core/Knowledge.py`:
- Around line 82-86: Replace the broad except Exception in the JSON/cache read
blocks (the try that loads formulate_query from query_path and the similar block
around lines 123-127) with targeted exception handling: catch FileNotFoundError,
json.JSONDecodeError, and OSError and set formulate_query = {} (or the
equivalent fallback) in those cases, and re-raise any other unexpected
exceptions so non-I/O bugs aren’t silently swallowed; reference the
variables/query_path and the formulate_query load logic to locate both spots to
update.

In `@gui_agents/s2_5/cli_app.py`:
- Around line 44-45: The except block in get_char (cli_app.py) is too broad;
narrow the exception handling to only ImportError and OSError (i.e., use except
(ImportError, OSError):) so we catch the expected module/load errors while
letting other exceptions surface, and keep the same fallback return input()
behavior inside that narrowed handler.

In `@gui_agents/s2/agents/agent_s.py`:
- Around line 349-353: Replace the broad except Exception around
json.load(open(reflection_path)) with targeted error handling: open the file
using a context manager (with open(reflection_path, "r") as f) and call
json.load(f), and catch only expected exceptions such as json.JSONDecodeError,
FileNotFoundError, and OSError/PermissionError to set reflections = {} (and
optionally log a warning); let all other exceptions propagate so unexpected bugs
are not silenced. Apply the same change to the other occurrence around lines
385-391 that uses reflection_path.

In `@gui_agents/s2/cli_app.py`:
- Around line 44-45: In the get_char function replace the broad "except
Exception:" fallback with a narrowed except clause "except (ImportError,
OSError):" so only import/OS-related failures fall back to input(); update the
except block that currently returns input() to use these two specific exceptions
(refer to the get_char function and its fallback except block).

In `@gui_agents/s2/core/knowledge.py`:
- Around line 88-93: Replace the blanket "except Exception" in the cache load
blocks so only expected I/O/parse errors are swallowed: catch FileNotFoundError
and json.JSONDecodeError (and optionally PermissionError) around the
open/json.load in the block that assigns formulate_query (and the similar block
around the other cache load at lines 129-133), set formulate_query = {} on those
specific exceptions, and let all other exceptions propagate so unexpected
runtime bugs are not silently ignored.
- Around line 272-275: The current try/except around
load_knowledge_base(self.episodic_memory_path) silently swallows all exceptions
and defaults kb to {}, which can cause unintended overwrites on subsequent
writes; update the block so it only catches expected read/parsing errors (e.g.,
FileNotFoundError, JSONDecodeError or whatever load_knowledge_base raises for
missing/corrupt data) and falls back to {} in those cases, but re-raises or
propagates any other unexpected exceptions so they aren’t hidden. Apply the same
change to the analogous block later (around lines handling the second load) and
reference the load_knowledge_base call and self.episodic_memory_path when making
the change.

In `@gui_agents/s3/bbon/comparative_judge.py`:
- Around line 21-25: The function extract_step_num currently catches all
exceptions; narrow the exception handling to only the expected types by catching
IndexError and ValueError explicitly (i.e., replace except Exception with except
(IndexError, ValueError)) so only parsing/split errors return 0 and other
unexpected exceptions bubble up.

In `@gui_agents/s3/cli_app.py`:
- Around line 45-46: Update the broad except in get_char to only catch the
expected import/terminal failures: replace "except Exception:" with "except
(ImportError, OSError):" (or the same tuple used in gui_agents/s1/cli_app.py) so
only import/OS-level terminal issues fall back to input(); keep the existing
fallback return input() and ensure the change references get_char to locate the
handler.

In `@osworld_setup/s1/run.py`:
- Around line 294-303: The broad except Exception in get_result should be
narrowed to only catch the expected errors: replace the generic except with
except (OSError, ValueError) around the float(open(os.path.join(example_path,
"result.txt"), "r").read()) call so only file/IO and conversion errors are
swallowed; keep appending 0.0 to all_result for those cases and leave other
exceptions to surface. Use the existing all_result and example_path variables
and the get_result function context when making this change.

In `@osworld_setup/s3/run_local.py`:
- Around line 356-365: The try/except in get_result currently swallows all
exceptions; narrow it to only catch I/O and parse errors by replacing the broad
"except Exception" with "except (OSError, ValueError)" around the
float(open(...).read()) read/parse block (and keep appending 0.0 on those
specific failures) so other unexpected exceptions propagate; reference the
get_result logic that builds all_result and the
float(open(os.path.join(example_path, "result.txt"), "r").read()) call when
making the change.

In `@osworld_setup/s3/run.py`:
- Around line 515-524: The except clause in get_result currently catches all
exceptions; narrow it to only catch OSError and ValueError (the expected errors
when opening/reading/parsing result.txt) and leave other exceptions to surface;
locate the try/except around reading os.path.join(example_path, "result.txt")
which appends to all_result and replace "except Exception" with "except
(OSError, ValueError)" so only file I/O and float conversion errors are handled.

ℹ️ Review info

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5caa76c and 10bfe8c.

📒 Files selected for processing (23)
  • gui_agents/s1/aci/LinuxOSACI.py
  • gui_agents/s1/aci/MacOSACI.py
  • gui_agents/s1/aci/WindowsOSACI.py
  • gui_agents/s1/aci/windowsagentarena/GroundingAgent.py
  • gui_agents/s1/cli_app.py
  • gui_agents/s1/core/AgentS.py
  • gui_agents/s1/core/Knowledge.py
  • gui_agents/s2/agents/agent_s.py
  • gui_agents/s2/agents/grounding.py
  • gui_agents/s2/cli_app.py
  • gui_agents/s2/core/knowledge.py
  • gui_agents/s2_5/agents/grounding.py
  • gui_agents/s2_5/cli_app.py
  • gui_agents/s3/agents/grounding.py
  • gui_agents/s3/bbon/comparative_judge.py
  • gui_agents/s3/cli_app.py
  • osworld_setup/s1/run.py
  • osworld_setup/s2/run.py
  • osworld_setup/s2_5/run.py
  • osworld_setup/s2_5/run_local.py
  • osworld_setup/s3/bbon/generate_facts.py
  • osworld_setup/s3/run.py
  • osworld_setup/s3/run_local.py

Comment on lines 670 to 673
try:
attribute_dict[f"{value_key}{attr_name}"] = str(attr_func())
except:
except Exception:
pass
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Silent except Exception: pass discards diagnostic info — add a log statement.

Any failure in attr_func() (e.g., a COM error or unexpected pyatspi error beyond NotImplementedError) is silently swallowed. Ruff S110 correctly flags this. A debug-level log preserves observability without changing behavior.

🔧 Proposed fix
             try:
                 attribute_dict[f"{value_key}{attr_name}"] = str(attr_func())
-            except Exception:
-                pass
+            except Exception as e:
+                logger.debug("Could not read value attribute %s for node %s: %s", attr_name, node_name, e)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try:
attribute_dict[f"{value_key}{attr_name}"] = str(attr_func())
except:
except Exception:
pass
try:
attribute_dict[f"{value_key}{attr_name}"] = str(attr_func())
except Exception as e:
logger.debug("Could not read value attribute %s for node %s: %s", attr_name, node_name, e)
🧰 Tools
🪛 Ruff (0.15.2)

[error] 672-673: try-except-pass detected, consider logging the exception

(S110)


[warning] 672-672: Do not catch blind exception: Exception

(BLE001)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@gui_agents/s1/aci/LinuxOSACI.py` around lines 670 - 673, The try/except
around calling attr_func() that sets attribute_dict[f"{value_key}{attr_name}"]
currently swallows all exceptions; change the except to log the exception at
debug level instead of passing so failures are observable. Specifically, inside
the except Exception block in LinuxOSACI.py where attribute_dict, value_key,
attr_name, and attr_func are used, call the module’s logger (or create one if
missing) to emit a debug log with a clear message including the attribute key
and the caught exception information (e.g., exception text/traceback) and then
continue preserving the current behavior (do not re-raise).

Comment on lines 90 to 94
try:
with open(trajectory_file, "r") as f:
trajectory_lines = f.readlines()
except:
except Exception:
pass
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Silent except Exception: pass on trajectory file read loses the I/O error.

If open(trajectory_file) or f.readlines() fails for any reason other than a missing file (e.g., permissions, encoding), the error is silently swallowed and trajectory_lines stays empty, causing all subsequent steps to lack action data. Narrowing to OSError and adding a log line improves debuggability.

🔧 Proposed fix
         try:
             with open(trajectory_file, "r") as f:
                 trajectory_lines = f.readlines()
-        except Exception:
-            pass
+        except OSError as e:
+            print(f"Warning: could not read trajectory file {trajectory_file}: {e}")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try:
with open(trajectory_file, "r") as f:
trajectory_lines = f.readlines()
except:
except Exception:
pass
try:
with open(trajectory_file, "r") as f:
trajectory_lines = f.readlines()
except OSError as e:
print(f"Warning: could not read trajectory file {trajectory_file}: {e}")
🧰 Tools
🪛 Ruff (0.15.2)

[error] 93-94: try-except-pass detected, consider logging the exception

(S110)


[warning] 93-93: Do not catch blind exception: Exception

(BLE001)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@osworld_setup/s3/bbon/generate_facts.py` around lines 90 - 94, Replace the
silent catch around opening/reading trajectory_file with a narrow OSError
handler: attempt the with open(trajectory_file, "r") as f: trajectory_lines =
f.readlines() block, and on failure catch except OSError as e: set
trajectory_lines = [] (or ensure it remains defined) and log the error including
trajectory_file and e (use the module/logger variable you have), rather than
using a bare except Exception: pass, so permission/IO errors are surfaced for
debugging.

@haosenwang1018
Copy link
Copy Markdown
Author

Closing per backlog policy; can revisit with narrower scope.

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.

1 participant