Try and catch

Try and catch

Hello Readers, I am coming with a more interesting topic try and catch .

Let's dive into the topic . Sometimes when we write code ,some syntax are written incorrectly and some gone wrong while execution.This gives error and causes disruption while the execution of code .This is handled with the exception handling.

Exception Handling is used to handle the error and exception while execution of the code. Error are of two types :-. 1. Syntax error occurs while writing code when the syntax is not proper and not understand by JavaScript interpreter. 2. Runtime error occurs while the code execution when the function is not defined.

We can handle only Runtime error . This is handled with the famous methods of JavaScript Try-catch.

Definition :- It is a method that deals with the errors of runtime. Syntax :- try { //block of code to test } catch { // block of code for addressing error. }

Try is used to check the code whether it is throwing error or not. If it throws error then it passes the code to the code. While catch is used to deal with the code which throws error in the try.The parameter is optional.

For example, here is the code :-

function trafficLight(color) { try { if(color==="red") { console.log("Stop"); } else if(color==="green"){ console.log("Go!!") } else { console.log("Wait") } catch{ console.log("Traffic light is not shown. ") }}}

Console.log(trafficLight("yellow"))

Try - catch - finally

function trafficLight(color) { try { if(color==="red") console.log("Stop"); } else if(color==="green"){ console.log("Go!!") } else { console.log("Wait") } catch{ console.log("Traffic light is not shown. ") }}

Console.log(trafficLight("yellow"))

Try-catch-finally

Syntax :-

try { //code to test } catch { //code for addressing the error } finally { //code to run after try-catch }