When executing JavaScript code, errors will most definitely occur. These errors can occur due to a fault from the programmer’s side or the input is wrong or even if there is a problem with the logic of the program. But all errors can be solved and to do so we use five statements that will now be explained.
- The try statement lets you test a block of code to check for errors.
- The catch statement lets you handle the error if any are present.
- The throw statement lets you make your own errors.
- The finally statement lets you execute code after try and catch. Â
The finally block runs regardless of the result of the try-catch block.
Below are examples, that illustrate the JavaScript Errors Throw and Try to Catch:
Example 1:
Javascript
try {Â Â Â Â dadalert("Welcome Fellow Geek!");}catch (err) {Â Â Â Â console.log(err);} |
Output: In the above code, we make use of ‘dadalert’ which is not a reserved keyword and is neither defined hence we get the error.  
Javascript
function geekFunc() {Â Â Â Â let a = 10;Â Â Â Â try {Â Â Â Â Â Â Â Â console.log("Value of variable a is : " + a);Â Â Â Â }Â Â Â Â catch (e) {Â Â Â Â Â Â Â Â console.log("Error: " + e.description);Â Â Â Â }}geekFunc(); |
Output: In the above code, our catch block will not run as there’s no error in the above code and hence we get the output ‘Value of variable a is: 10’. 
try {
Try Block to check for errors.
}
catch(err) {
Catch Block to display errors.
}
Example: In this example, we will see the usage of try-catch block in javascript.
Javascript
try {Â Â Â Â dadalert("Welcome Fellow Geek!");}catch (err) {Â Â Â Â console.log(err);} |
Output: 
Example: In this example, we will see how a throw statement is used to throw an error in javascript.
Javascript
try {Â Â Â Â throw new Error('Yeah... Sorry');}catch (e) {Â Â Â Â console.log(e);} |
Output: 
try {
Try Block to check for errors.
}
catch(err) {
Catch Block to display errors.
}
finally {
Finally Block executes regardless of the try / catch result.
}
Example: In this example, we will learn about the final statement of Javascript.
Javascript
try {Â Â Â Â console.log('try');} catch (e) {Â Â Â Â console.log('catch');} finally {Â Â Â Â console.log('finally');} |
Output: The Finally Block can also override the message of the catch block so be careful while using it.

[…] this, we will declare a try-catch block inside this method and inside the try-block, we will declare a variable inside which we will […]