Javascript try,catch and finally : Error handling

When we run Javascript code unexpected errors can happen but how to handle these errors…
Handling the errors are necessary for providing a better end user experience and Javascript provides some features to efficiently handles the errors
Try statement – Try statement checks for errors in a block of code.
Consider the following code,the httpGet function send a Get request to a dummy api
This successfully runs , but what if we provide a wrong api url


As you can see try and Catch Statement lets us handle errors while the code is being executed
Throw Statement
Throw statement lets us throw custom errors.The error thrown can be a string,number or an object
Consider the following example
Here the request was successful but we expected a.userId to be 100.Since the result was not the expected one we throw a custom error.
 ‘Not Expected Result’;
Using the try and catch statements together, we can control the  program flow and generate custom error messages.
Finally statement
Finally statement ,lets us execute a block of code irrespecitve of the results of the try and catch.Consider the above example in which we throws a custom error.Now we add a finally statement to it which will be executed even though the error was thrown

The code inside the finally block is executed.Finally can be useful in cases like to hide a loading image irrespective of the outcome of an Api request.

No Comments

Leave a Reply

Your email address will not be published. Required fields are marked *