Not every exception should escape your function — sometimes the right move is to catch it and fall back to a safe default.
Write a function that converts text to an integer, falling back to a default value if the text isn't a valid number:
parse_int_or_default(text, default)
If text can be converted with int(text), return that. Otherwise, return default. Either way, this function should never raise — malformed input is expected, not exceptional.
parse_int_or_default("42", 0) // → 42
parse_int_or_default("abc", 0) // → 0
parse_int_or_default("", -1) // → -1
The previous problems all let exceptions propagate out — that's the right call when the caller should decide what a failure means. This one is the opposite case: the caller just wants an int, and doesn't care whether it came from the input directly or a fallback. The exception should never leave this function at all.
def parse_int_or_default(text, default):
try:
return int(text)
except ValueError:
return default
The try block attempts the conversion. If int(text) succeeds, that return fires immediately and the except block is skipped entirely. If it raises ValueError (which it does for anything that isn't a valid integer literal, including an empty string), control jumps to except ValueError and returns default instead.
This is the judgment call that matters more than the syntax: in Safe Divide, dividing by zero was a genuine error the caller needed to know about. Here, malformed text input is an expected, normal possibility — think of a config file with a typo'd number, or a user who leaves a field blank. Swallowing the exception and substituting a sensible default is exactly the right behavior, not a shortcut to avoid handling the error properly.
The skill isn't "catch everything" or "catch nothing" — it's recognizing which failures are truly exceptional (let them propagate) and which are routine and expected (handle them locally).
def parse_int_or_default(text, default):
try:
return int(text)
except ValueError:
return default
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.