javascript try catch example function
try catch is a good way to stop errors breaking your javascript.
here is the example from the firefox mozilla with a basic try catch logging the error to your console, rather than just breaking all the javascript on your page.
then after this try catch i will add another console log to see if the code is still functioning on the rest of the scripts.
so you can see if you check your console log that the try catch still throws an error but then the scripts continue to run on the page, so if i called the non existant function without the try catch it would not run the console log below that error message.
So if possible all functions should be run in this way to prevent script breaking calls.
Here you can see the console output showing the console log after the error.
When running this test in brave i get the error (which is expected):
(index):378 ReferenceError: nonExistentFunction is not defined
at (index):376
if i run this without the catch it will not run any further code on the page and just return an error.
Here is the console after just calling the function with no try and catch statement, and it no longer runs any code after this error.
Javascript
try {
nonExistentFunction();
} catch (error) {
console.error(error);
// expected output: ReferenceError: nonExistentFunction is not defined
// Note - error messages will vary depending on browser
}
console.log('more tests... ');
// and this will break all the js on the page with an error.
nonExistentFunction();
console.log('test after breaking function');
External Link for javascript try catch example function