Try Catch
There will be mistakes in certain programs, no matter how proficient you are at programming. Unexpected user input, an incorrect server response, or any other reason might generate these problems. Try catch in JavaScript allows you to catch mistakes and perform something more acceptable instead of dying. In this article, we'll look at how JavaScript utilizes try-catch to handle exceptions in the order listed below.
In JavaScript, handling with Runtime Errors
Error handling has progressed from the days of Netscape and Internet Explorer 4. You don't have to accept what the browser throws at you in the event of a JavaScript error; instead, you may take control of the situation. When a JavaScript error occurs, the try-catch statement in JavaScript aids in rerouting.
Try-catch, together with other defensive coding approaches like Object detection and the onError event, allows you to maneuver around mistakes that would have previously stopped your script dead in its tracks.
What is Try Catch in JavaScript?
Exception handling has been added to JavaScript in recent versions. To manage exceptions, JavaScript uses the try-catch construct and the throw operator. You can capture programmer- and runtime-generated exceptions, but not syntax problems with JavaScript.
The try statement is used to specify a block of code that will be checked for problems while it runs. The catch statement, on the other hand, is used to specify a block of code that will be run if the try block fails.
The statements that JavaScript tries to capture are in pairs:
try {
}
catch(err) {
}
When an exception occurs in the try block, the exception is thrown into err, and the catch block is run.
Try Catch Example
Here's a try-catch example in JavaScript:
var message, x;
message = document.getElementById("p01");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "is empty";
if(isNaN(x)) throw "is not a number";
x = Number(x);
if(x > 10) throw "is too high";
if(x < 5) throw "is too low";
}
catch(err) {
message.innerHTML = "Input " + err;
}
finally {
document.getElementById("demo").value = "";
}
}
Top comments (0)