To handle any error which occurs while execution, the methods of error handling are used.
When an error occurs, the content of this stack is printed as an output, enabling the programmers to trace the function calls in a backward direction and figure out from where the error has been originated. It also tells the file name and the line number where the error occurred for some specific reasons. It’s better used for debugging purposes.
Example 1: The following code creates a function that checks whether the entered value is a number or not. If not found a number then it throws an error whose stack contents is printed in an alert box as shown.
Stack is traced to find an error, from the output it’s clear that first the name of the file is shown where an error occurred and then the line along with the reason for the error occurrence. We can also log this error into our console.
Example 2: We are trying to take a method where the error is raised by the system and not by the user.
We can see how Error.prototype.Stack works for all types of errors whether it is user-defined or not. We can also use other properties of the error class to investigate more about them, their name, messages, and many more.
- Before Clicking the Button:
- After Clicking the Button: