Handling exceptions

Objectives

  • Use try, throw, and catch
  • Use console.assert() to catch errors

Try, throw, catch

  • You can check for exceptions using the "try/catch" structure.
  • You can throw an exception in code using the "throw" keyword.
  • If an exception is thrown in a function and is not inside a "try" block, then the rest of the code in the function does not execute.
  • Any code that might cause an exception should be in a "try" code block.
  • A "catch" code block follows the "try" block.
  • If an exception is encountered in the "try" block, execution immediately jumps to the "catch" block.
  • Keep in mind that any code in the "try" block following an exception is not executed.
  • An optional "finally" block can follow the "catch" block. The "finally" block code will run whether there was an error or not.

Exception examples

Using assert

  • Note: console.assert should work well on Chrome, but may not be supported (or supported well) in other browsers
  • console.assert() is used for catching internal logic errors
  • console.assert() should not be used for validating user input
  • console.assert(expression): will cause an error message to print on the console if expression evaluates to false
  • console.assert(expression, message): will cause an error message to print on the console if expression evaluates to false; the message will be included with the error message

Assertion examples