Lesson 3 of 8

Where to put try

Goal

Keep it narrow and lose no errors

01

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.

02

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
  1. The function is defined
  2. Turns a valid object string into an object
  3. Also parses an array string
  4. Returns the fallback for invalid text and doesn't throw
  5. Empty text gives the fallback too
  6. The list shows four items
03

Hints

0/3
Track lessons0 of 8 done

Learn how to read an error message, check inputs before you use them, and catch the errors worth handling.

Intermediate level, 8 lessons, 1.5 hours in total.

index.html
Preview
index.html100%
–/6

Press “Run and check” to grade your code.

6 checks listed under “Your task”.

Track lessons0 of 8 done

Learn how to read an error message, check inputs before you use them, and catch the errors worth handling.

Intermediate level, 8 lessons, 1.5 hours in total.