Skip to content

fix(maths): use specific exception types in collatz_sequence#14769

Open
fauzan171 wants to merge 1 commit into
TheAlgorithms:masterfrom
fauzan171:fix/collatz-exception-types
Open

fix(maths): use specific exception types in collatz_sequence#14769
fauzan171 wants to merge 1 commit into
TheAlgorithms:masterfrom
fauzan171:fix/collatz-exception-types

Conversation

@fauzan171
Copy link
Copy Markdown

Summary

Replace the generic Exception with appropriate specific exception types (TypeError and ValueError) in the collatz_sequence() input validation.

Changes

  • Split the combined if not isinstance(n, int) or n < 1 check into two separate checks
  • Raise TypeError when input is not an integer (e.g., float, string)
  • Raise ValueError when input is an integer but not positive (e.g., 0, -1)
  • Updated doctests to match the new exception types

Why

Using Exception is a Python anti-pattern. Specific exception types allow callers to handle different error cases appropriately:

  • TypeError: wrong input type
  • ValueError: correct type but invalid value

This follows the same pattern used by other functions in this repository (e.g., juggler_sequence(), liouville_lambda(), twin_prime()).

Checklist

  • All doctests pass
  • Consistent with exception handling patterns elsewhere in the repo

Replace generic Exception with TypeError for non-integer inputs and ValueError for non-positive integers. Split the combined validation check into two separate checks for clearer error reporting. This follows Python best practices for exception handling.
@algorithms-keeper algorithms-keeper Bot added enhancement This PR modified some existing files awaiting reviews This PR is ready to be reviewed labels Jun 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting reviews This PR is ready to be reviewed enhancement This PR modified some existing files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant