BASIC ERROR HANDLING TRY, CATCH, FINALLY, THROW STATEMENTS IN JAVA SCRIPT

Error can be coding errors made by the programmer. Errors due to input or other unforeseen things. I will write how to handle errors in Java Script. Error handling is used most when working with data from other sources or user input since those can be unreliable.It is common to see error handling associated with Ajax calls and asynchronous code. Error handling uses the keywords “try”,”catch”, “finally” and “throw”

  • try {} statement test a block of code for errors.
  • catch {}statement handle the error.
  • throw{} statement can make a custom errors.
  • finally{} statement execute code after try{}&catch{} regardless of the result.

Let’s work on some codes for try{},catch{},finally{} statements.

TRY & CATCH AND FINALLY STATEMENTS

try {
console.log('Start of try runs');//here is some code going to runs
unicycle;// this part is the error.

console.log('End of try runs -- never reached');
//it's going to try some more code here
} catch(err) {
//its gonna catch the error
console.log('Error has occured: ' + err.stack);} finally {
console.log('This is always run'); // here is final statement
}
console.log('...Then the execution continues');
The following flowchart illustrates the flow of the try...catch statement:

In the beginning we start up with try{} runs when its reaches the error. Since its reached the error there, it never go to next statement.

(console.log(‘End of try runs — never reached).

When the error is reached it will go straight to the catch{} statement. If you log in the codes above on your console. You will see it clearly.

Go to console in browser ..

“Start of try runs”

(‘Error has occured: ReferenceError”unicycle is not defined at pen.js:14:3");

If we pass in error object to the catch statement and console.log(‘Error has occured: ‘ + err.stack); it’s going to show this part on your console. When the errors occurs JavaScript generates an object contains details about it. So This is error object.

“This is always run”

“….Then the execution continues”

Error object has two main properties (name:”ReferenceError message:”unicycle is not defined”)+(stack:”at pen.js:14:3")

Finally Statements

Whether of not if the error happens we are going to always run the code in the finally statement.(“This is always run”)then you can see the execution (“….Then the execution continues”) just after try catch statement is over it . Now for the try catch to work the code must be runnable in other words should be valid in Java Script. It does not work any syntax error if you have any open “{ “ your code will be brake.Its call parse time error. Try-catch only handles runtime errors so code has to be able to run.

THROW STATEMENTS

You can also create your own error with throw{} statement. I will write throw{} error in context of a more realistic use case for try catch statements.

I will pretend like to get data from server JSON data sometimes through an AJAX call . I am going to parse data from server and if there there is no “user.name”, we are going to throw a new syntax error and complete data “no name”. if we don’t get name from server we will throw a new syntax error and put incomplete “no name”. You can actually throw error as a numbers or strings or booleans. You can also create a new syntax error and you can add a message. Syntax error going to be name and message in the error. if you run code below you will see what is going to log in your console.

let json = '{ "age": 30 }';

try {

let user = JSON.parse(json);
if (!user.name) {
throw new SyntaxError("Incomplete data: no name");
}

console.log( user.name );

} catch(e) {
console.log( "JSON Error: " + e );
}

Here’s the other specification example :

  • Adding the .hidden class to the error modal in the HTML so it does not appear when the page first loads
  • When a user clicks on an empty heart (“Recognizing events”)
  • Invoking mimicServerCall to simulate making a server request
  • mimicServerCall randomly fails to simulate faulty network conditions
  • When the server returns a failure status
  • Responding to the error using a .catch(() => {}) block after your .then(() => {}) block.
  • Displaying the error modal by removing the .hidden class
  • Displaying the server error message in the modal
  • Using setTimeout to hide the modal after 5 seconds (add the .hidden class)
const EMPTY_HEART = '♡'const FULL_HEART = '♥'const glyphObject = {'♡':FULL_HEART,'♥':EMPTY_HEART}const colorState = {"red":"","":"red"}///let likeButtons = document.querySelectorAll(".like")for (el of likeButtons){el.addEventListener("click", (e) => {mimicServerCall().then((respond) => {e.target.innerText = glyphObject[e.target.innerText]e.target.style.color = colorState[e.target.style.color]}).catch((error) => {document.getElementById("modal").className = ""setTimeout(function() {document.getElementById("modal").className = "hidden"}, 5000);})})}

--

--

--

Software Engineer | Ruby on Rails | JavaScript | HTML5 | CSS | PostgreSQL | React | Redux

Recommended from Medium

Binary Tree —  BFS, DFS — JavaScript

Tricky C++: Making Things Constant

Overscripted! Digging into JavaScript execution at scale

4 best JavaScript date libraries

A complete guide to CSS Modules in React (Part-2)

Why Use React Native for Your Next IoT Project?

10 interesting topics of JavaScript

Burst-fire enemy and zig-zag movement

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
Soner Mezgitci

Soner Mezgitci

Software Engineer | Ruby on Rails | JavaScript | HTML5 | CSS | PostgreSQL | React | Redux

More from Medium

I built a tool to curate my own code template library

5 Must Know Lodash Methods

Generic Type Inference through Function Arguments in TypeScript

Why PHP, goto, and bubblesort, are all good, actually 👍

A collection of rainbow coloured bubbles.