Exception handling in javascript

  • Dividing a number by zero: This results in infinity, thus throwing an exception.
  • When a requested file does not exist in the system.
  • When the user provides the wrong input.
  • When the network drops during communication.

JavaScript error types

  1. Syntax Errors: These are errors that cannot be interpreted by the computer. These errors stop the program from working.
  2. Runtime Errors: These errors take place during execution. The errors get detected when your program runs. It crashes or raises an exception. Thus, exception handlers handle exception errors.
  3. Logical Errors: These types of errors do not throw an error or an exception at all. This is because they result from the code not doing what the developer intends it to. It’s challenging to find logical errors. They can only be found through thorough testing.

Error objects

  • Name: It gives the error name.
  • Message: It sets or returns the error message in the form of a string.
  • RangeError: RangeError exceptions occur when a numeric value is outside the specified range.
  • ReferenceError: A ReferenceError exception occurs when undeclared variables are used. These exceptions commonly occur due to spelling errors on variables.
  • Syntax Error: A Syntax Error exception occurs when JavaScript language rules get broken.
  • TypeError: A TypeError exception occurs when a value is different from the one expected.
  • URIError: A URIError exception is raised by encodeURI() and decodeURI() methods.

How to handle exceptions in JavaScript

Key Terms

  • A try-catch-finally statement is a code or program that handles exceptions.
  • The try clause runs the code that generates exceptions.
  • The catch clause catches exceptions that are thrown.
  • A finally clause always gets executed.
  • The throw statement generates exceptions.

Try catch statements

function myFunction() {
const j = 70;
try {
allert("The value of j is : " + j);
} catch (error) {
alert("Error: " + error.message);
}
}

Try catch finally statements

function myFunction() {
const j = 70;
try {
alert("The value of j is : " + j);
} catch (error) {
alert("Error: " + error.message);
} finally {
alert("Finally: Finally gets executed")
}
}

Throw statements

function myFunction() {
const x = 50;
const y = 0;
try {
if (y === 0) {
throw ("This is division by zero error");
} else {
const z = x / y;
}
} catch (error) {
alert("Error: " + error);
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store