How to Handle Errors in JS with try/catch
2 min readMay 6, 2021
What is a try/catch in JavaScript?
A try/catch is basically used to handle errors in JavaScript. You use this when you don’t want an error in your script to break your code.
try/catch block statements
- trow error statement
But we can take it a step further by actually throwing an error with the JavaScript constructor errors.
Actually, JavaScript categorizes errors into six groups:
- EvalError — An error occurred in the eval function.
- RangeError — A number out of range has occurred, for example
1.toPrecision(500)
.toPrecision
basically gives numbers a decimal value, for example, 1.000, and a number cannot have 500 of that. - ReferenceError — Using a variable that has not been declared
- syntax error — When evaluating a code with a syntax error
- TypeError — If you use a value that is outside the range of expected types: for example
1.toUpperCase()
- URI (Uniform Resource Identifier) Error — A URIError is thrown if you use illegal characters in a URI function.
The Finally statement
The finally statement acts like neutral ground, the base point, or the final ground for your try/ catch block. Finally, you are basically saying no matter what happens in the try/catch (error or no error), this code in the finally statement should run.For example:
let data=prompt("name")
try{
if(data==="") throw new Error("data is empty")
else alert(`Hi ${data} how do you do today`)
} catch(e){
alert(e)
} finally {
alert("welcome to the try catch article")
}
Conclusion
In this article, I have tried to explain the following concepts relating to try/catch:
- What try /catch statements are and when they work
- How to throw custom errors
- What the final statement is and how it works
- How Nesting try/catch statements work
- How to rethrow errors