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
index.ts
and:
  1. Throw an error when the input isn't a valid number
  2. Wrap the conversion in a try/catch
  3. Set resultMessage to 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

Please set the playground first

Loading "Throwing and Catching Errors"
Loading "Throwing and Catching Errors"
Login to get access to the exclusive discord channel.
Loading Discord Posts