Lesson 3 of 8
Where to put try
- 13 min
- 6 checks
- 3 hints
- Go to task
Goal
Keep it narrow and lose no errors
Explanation
There are two common mistakes with try/catch. The first is wrapping the whole function in it, so you can't tell which line failed. The second is leaving catch empty, which hides the error and leaves the page half working without a single message.
The rule: put only the line that can fail inside try, and make catch do something real, like return a fallback value, show the user a message, or rethrow the error after adding an explanation of what was going on.
Keep everything that can't throw out of it, too. Code that never fails but sits inside a try misleads whoever reads it after you.
Your task
Write the function safeParse(text, fallback) so it returns the parsed value on success and the fallback on failure, without ever throwing an error.
Checks
6 checks- The function is defined
- Turns a valid object string into an object
- Also parses an array string
- Returns the fallback for invalid text and doesn't throw
- Empty text gives the fallback too
- The list shows four items