In JavaScript, errors are runtime issues that occur during the execution of a script. These errors can halt the execution of the program if not handled properly. JavaScript provides various error types to help developers identify and troubleshoot issues effectively.
Types of JavaScript Errors
- Syntax Errors: Occur when the code violates the syntax rules of JavaScript.
- Reference Errors: Occur when a non-existent variable is referenced.
- Type Errors: Occur when an operation is performed on a value of the wrong type.
- Range Errors: Occur when a value is not within the set or allowed range.
- Eval Errors: Occur due to incorrect usage of the
eval()
function. - URI Errors: Occur when
encodeURI()
ordecodeURI()
functions are misused.
1. Syntax Errors
A syntax error occurs when the JavaScript engine encounters tokens or code that do not conform to the syntax rules.
try { eval('alert("Hello);'); // Missing closing quotation mark } catch (error) { console.log("Syntax Error: " + error.message); }
2. Reference Errors
A reference error occurs when trying to access a variable that is not defined.
try { console.log(x); // x is not defined } catch (error) { console.log("Reference Error: " + error.message); }
3. Type Errors
A type error occurs when a value is not of the expected type.
try { let num = 5; num.toUpperCase(); // toUpperCase() is not a function for numbers } catch (error) { console.log("Type Error: " + error.message); }
4. Range Errors
A range error occurs when a number is outside its allowed range.
try { let num = 1; num.toPrecision(500); // Precision is out of range } catch (error) { console.log("Range Error: " + error.message); }
5. Eval Errors
Eval errors occur when there is an issue with the eval()
function. Although eval()
errors are rare, they can still happen.
try { eval("alert('Hello)"); // Syntax error inside eval } catch (error) { console.log("Eval Error: " + error.message); }
6. URI Errors
URI errors occur when using malformed URIs in functions such as decodeURI()
or encodeURI()
.
try { decodeURI("%"); // Invalid URI component } catch (error) { console.log("URI Error: " + error.message); }
Custom Error Messages
You can throw custom errors using the throw
statement to provide more meaningful error messages.
try { let age = -5; if (age < 0) throw "Age cannot be negative"; } catch (error) { console.log("Custom Error: " + error); }
Conclusion
JavaScript provides a robust error handling mechanism to catch and manage errors effectively. By understanding the different types of errors and how to handle them, you can make your code more reliable and user-friendly.