JavaScript try/catch statements
If you’re coding, there’s gonna be errors…
Errors aren’t necessarily a bad thing, solving errors means that progress is being made as an application comes together. That doesn’t make errors fun to deal with, and even after the application is finished who knows what some user could do to make the application break in ways never thought of before? This is where the practice of error handling comes into play; creating a plan of action to take care of any unforeseen errors that may happen when users start using a project in the real world. One JavaScript function that can be used in error handling is the try/catch statement.
The basics of a try/catch statement are exactly what it sounds like. The application will run whatever code in in the try section and if it catches any errors there will be a response to handle said error instead of the entire application breaking.
The general syntax for a try/catch statement looks like this:
try {
// block of code to test out
}
catch (err) {
// block of code to handle errors
}
Other parts that can be added in to error handling are throw which us a function to create custom errors, nice for when you want certain text to appear or maybe to navigate to another part of the application.
There is also finally which will run whatever block of code is in side regardless of the result of the try/catch.
These statements work very well for handling user input. If we used an example of some sort of login the try/catch might look like this:
try {
//code that takes the user's login info and attempts to authenticate
}
catch (err) {
//code that sends an error message, maybe "Invalid login credentials"
}
Using try/catch statements in JavaScript are a great way to protect the application from breaking from unknown errors. It’s a bit of a blanket statement, as you might not know exactly what errors might show up and can’t prepare for anything a try/catch statement is a great way to handle errors that might be outside of the programmers control.