Recap Javascript Fundamental Concept

Nabil Woalid Rafiu
2 min readMay 6, 2021

What is try…catch?

try…catch are mainly used to catch error in a script so that the script can do something reasonable at the same time ignore dying. try and catch are two main blocks of try…catch

Why try…catch are used?

You are a programmer! So, one of your enemies is getting errors while programming. We can get errors due to wrong input or other unforeseeable things. When an error occurs javascript may not show you the desired output. It may show you an error message instead.

Here, the try statement helps you to test a block of code for errors.

And, the catch statement lets you handle the error.

How try…catch works?

1. try{…} is executed. If there are no errors catch is ignored and trial runs.

2. catch(err) runs when it goes wrong with try{..}. That means when an error occurs catch(err) is executed.

Example:

1.try{…} runs and catch(err) ignored

try{

alert(‘try is running’)

} catch(error){

alert(‘no error’)

}

2.try{…} ignored and catch(err) runs

try{

error

} catch(error){

alert(‘error has occured’)

}

Error Object

Javascript always creates an object when an error occurs. The Object contains details about this error.

try{

alert(‘try is running’)

} catch(error){

alert(‘no error’)

}

Here, error is an object. Error contains two message name and message.

try…catch in real life

let json = ‘{“name”: “Rakib”, salary: “30000”}’

let user = JSON.parse(json);

alert(user.name)//Rakib

alert(user.salary)// 30000

In this case , if json structure is not valid , it will show error

Example:

let json = “{invalid json}”;

try{

let user = JSON.parse(json);

} catch(error){

alert(error)

}

Here, You will get errors as JSON is not formed correctly.

Throw Operator:

The throwing operator generates an error.

Syntax: Throw <error object>

You can use anything as an error object. But using the name and message properties as an object is reasonable.

Caching API:

Cach API allows service workers to have control over resources(HTML pages, CSS, JavaScript files, images, JSON, etc) to be cached. The catch you will create will be created for your domain and you can add multiple caches for the same domain. You can access it by caches.keys()

--

--