Error handling: try/catch/finally

Things go wrong. Files don't exist. JSON is malformed. APIs return garbage. Good code anticipates failure and handles it cleanly — without crashing everything.

Write a function parseAndDouble(input) that:

  1. Parses input as a JSON number
  2. Returns that number doubled
  3. If parsing fails (input is not valid JSON or not a number), catches the error and returns -1 instead

Your program receives comma-separated inputs. For each, call parseAndDouble and print the result.

Input:  5,abc,3.5,null,10
Output: 10
        -1
        7
        -1
        20

Constraints

  • Use try/catch (not if/else checks).
  • null, strings, booleans, and invalid JSON all count as failures (return -1).
  • Only JSON numbers (integers and floats) succeed.
Ad SpaceGoogle AdSense active for guests & free-tier learners.