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
and:
- Throw an error when the input isn't a valid number
- Wrap the conversion in a
try/catch - Set
resultMessageto show either the parsed value or the error message
In a
catch block, the error value is unknown. Use
error instanceof Error before reading error.message.π MDN - throw
π MDN - try...catch


