• Tutorials Logic, IN
  • +91 8092939553
  • info@tutorialslogic.com

Error Handling in JavaScript

Error Handling

While executing the JavaScript code, different errors may occur. These errors can be a syntax error, logical error, and runtime error. There are several ways of handling them:-

The try and catch:- The try statement is a block of code that lets us test a block of code for errors, while the catch statement is a block of code that lets us handle the error.

										    
											try {
												expression;
											}
											catch(error) {
												expression;
											}
											
										
										    
											var a = 10;
											var b = 20;
											try {
												console.log(a + b);
											}
											catch(error) {
												console.log(error);
											}
											
										

The throw:- The throw statement allows us to create a custom error.

										    
											var x;
											try {
												if(x == "") throw "Empty";
												if(isNaN(x)) throw "Not a number";
											}
											catch(error) {
												console.log(error);
											}
											
										

The finally:- The finally statement is a block of code that lets us execute code, after try and catch, regardless of the result, which means finally block will always execute.

										    
											var x;
											try {
												if(x == "") throw "Empty";
												if(isNaN(x)) throw "Not a number";
											}
											catch(error) {
												console.log(error);
											} finally {
												console.log("Finally block will always execute!")
											}