Throwing and Catching Errors
Errors
π¨βπΌ We need to convert user input into a number. If the input is invalid, we
should throw an error and handle it gracefully so the program can keep running.
Sometimes the best control flow is to stop execution and report a problem:
try {
const parsedValue = Number('not-a-number')
if (Number.isNaN(parsedValue)) {
throw new Error('Something went wrong')
}
} catch (error) {
console.error('Caught an error:', error)
}
π¨ Open
. The starter provides:
rawInput = 'not-a-number'resultMessagestarting as''hadErrorstarting asfalse
Parse
rawInput as a number inside a try/catch. If the input is not a valid
number, throw an error whose message is exactly
Invalid number: not-a-number (the prefix Invalid number: plus the raw
input). On success, set resultMessage to describe the parsed value using the
format Parsed value: <number>. On failure, set hadError to true and set
resultMessage to Error: <error message> (so the thrown message appears after
the Error: prefix).Export
resultMessage and hadError.Required exports
resultMessage, hadErrorCompletion criteria (with this fixture)
hadErroristrueresultMessageis exactlyError: Invalid number: not-a-number
Edge cases to keep in mind: valid numeric strings should succeed and set
resultMessage to the success format (no error); invalid input must throw and
be caught without crashing the program.In a
catch block, the caught value is typed as unknown. Narrow it before
you read properties like a message string.π MDN - throw
π MDN - try...catch


