JS: Error Handling | JavaScript

JavaScript Error Handling

JavaScript error is an unexpected situation arises either during coding or running the code. Error are of two categories:

  1. Syntax error
  2. Runtime error

Syntax Error

JavaScript syntax errors raised due to incorrect syntax.

var str = 'PiTribe"; SyntaxError: '' string literal contains an unescaped line break

The variable str have to hold PiTribe and should be enclosed either within "" or '', but the value started with single-quote and ended with double-quote that is not compliaced with the JavaScript sysntax.

Runtime Error

JavaScript runtime error are the unexpected, exceptional situation. Runtime errors are thrown while the JavaScript code in progress. JavaScript runtime error handling is similar to c, Java and c# exception handling.

Math is the built-in class in JavaScript and PI its property. We will use Math.PI in the these examples. We will also use Math.PI() as function to let JavaScript throw error.

try

try block is a code region where error is expected:

try{ /* threatening code in this block */ }

try block must be followed by catch and/or finally block(s), will discussed in following sections

catch

catch block is executed just after the preceding try block. catch block is executed if and only if preceding try throws an error.

var v; try{ v = Math.PI(); } catch(err){ console.log(err); //show error }
try and catch blocks handle the runtime errors only. Syntax errors must be fixed to start the code running successfully.

finally

finally block is executed in either situation i.e. either an error thrown in the try block or exectued successfully. finally block exectued after the catch block

var v; try{ v = Math.PI(); } finally{ console.log(v); } TypeError: Math.PI is not a function

If try and finally blocks defined but the catch block not defined, then error will be thrown but finally block still exectued.

In some cases, Software Developers ommit catch block to let the caller function handle the error (exceptional situation).

try catch finally

JavaScript try catch finally blocks should be defined whenever possible to overcome unexpected or overlooked situations.

var v; try{ var str = prompt('enter a value'); v = parseFloat(str); if(!v) multiply(v); } catch(err){ console.log(err); //show error } finally{ console.log(v); }

The above code may be or may not be throw error, depending upon the input but will not break the flow of the program in any case.

When the code in try block runs successfully i.e. without runtime error:

var v; try{ v = Math.PI; } catch(err){ console.log(err); //show error } finally{ console.log(v); }

Error object

JavaScript standard error object contains two members:

name
The name (or say type) of the error
message
The reason of the error

Web browsers have their specific properties of error object in addition to JavaScript standard properties.

var v; try{ v = Math.PI(); } catch(err){ console.log(err.name); //show error name console.log(err.message); //show error message }

Error Types

RangeError

JavaScript throw RangeError when a value is beyond the maximum/minimum allowed value of the primitive data type.

try{ var x = 50; var fractions = x.toFixed(101); //error } catch(err){ console.log(err); } RangeError: precision 101 out of range

JavaScript Number class has toFixed, allows values 0 to 100. The code above throws error because 101 is more than its range.

ReferenceError

JavaScript throw ReferenceError on the use of undeclared variable.

try{ var x = z; //error } catch(err){ console.log(err); } ReferenceError: z is not defined

The code above throw error because z is not declared.

SyntaxError

JavaScript throw ReferenceError on the use of undeclared variable.

try{ var str = "PiTribe'; //error } catch(err){ console.log(err); } SyntaxError: "" string literal contains an unescaped line break

JavaScript throw SyntaxError because the string should be enclosed either within "" or '', but the value started with double-quote and ended with single-quote. You may observe that SyntaxError not printed console as other erros like RangeError or ReferenceError do. This is because the program could not started i.e the SyntaxError doesn't allow to run successfully.

Let's add another line at the start of the program above:

console.log('Checked!'); var str; try{ str = "PiTribe'; //error } catch(err){ console.log(err); } SyntaxError: "" string literal contains an unescaped line break

Important is that the first line console.log('Checked!'); did not show the text in console.logChecked! just because the program could not started just because of the syntax error(s) (SyntaxError).
The interpreter will not execute var str = "PiTribe'; but still the SyntaxError error does not let the program start successfully.
In short program need to resolve all errors to let the program start.

The SyntaxError (syntax errors) must be resolved to let JavaScript program start successfully no matter the syntax error is at the last line or the JavaScript interpreter will not reach that statement of code.

Catch Errors in eval expressions

Lets make change in the above example code:

console.log('Checked!') try{ var str = eval('console.log("PiTribe)'); //error in eval } catch(err){ console.log(err); } Checked! SyntaxError: "" literal not terminated before end of script

Now, console.log('Checked!'); shows up the text in console.log Checked! just because the program started successfully without syntax error (SyntaxError) but later eval caused SyntaxError as the code within eval caused.

The code within eval throw SyntaxError (syntax errors) if any but that does not become the cause to start the program.

lets make a change in the example code above. Put var str = eval('console.log("PiTribe")'); line under the if (false) condition and observe the browser's console if the program throws error?

TypeError

JavaScript throw TypeError when an operation is performed to with unsupported type.

try{ var x = "PiTribe".toFixed(3); //error } catch(err){ console.error(err); } TypeError: "PiTribe".toFixed is not a function

The code above throw error because "PiTribe" is a String whereas toFixed is the function for Number type.

URIError

JavaScript throw URIError when malformed URI sequence provided.

try{ var x = decodeURIComponent('%'); //error } catch(err){ console.error(err); } URIError: malformed URI sequence

The code above throw error because '%' is not a valid URI component. Instead, '%40' or likewise work beacuse URI encodes "@" as "%40".

throw Custom Errors in JavaScript

JavaScript allows to throw custom errors (user defined errors programmatically).

function cube(p){ if(typeof p !== "number"); throw "Number is required"; return p*p*p; } Error: Number is required

The name of the programmatically thrown error is Error and message is the text after the throw keyword. In the code above, the message is Number is required.

Error class is the custom error type.

Notes

  1. try must accompained with catch, finally or both
  2. if catch ommited after try block, exception will be thrown even in that case
  3. throw keyword is used to throw error by a programmer