Hypothetically - let's say I have some JavaScript to handle the clicks of three different buttons:
$("#working").click(function () {
alert("Seth Rollins is the greatest champion of all time.");
console.log("WWE World Heavyweight Champion");
});
$("#fix-this-error").click(function () {
alert(this_should_not_show_up_in_the_console);
console.log("This won't show");
});
$("#should-error").click(function () {
alert(oipewavqn2389tvb3t8ahwleuhtvab3iwuthabvlewiuweaqhaoiuhva98r3b2);
console.log("This won't show either");
});
The first one will work as it alerts a string, and it will log to the console the message that is written after the alert.
The second and third functions will not work because they are trying to alert variables that are not defined. Their subsequent console.logs
will not output anything.
My Question: Is it possible to prevent the error from the second function from outputting to the console while maintaining the following properties?:
console.log
still should not executeEdit: Here is a fiddle to play around in - https://jsfiddle.net/5m40LLmm/2/
SUPER EDIT: I don't want the execution of logic in the second function to really change. I want the error to be thrown, and the .click()
handler should exit before it reaches console.log as it does now. I just want to prevent the error from being shown. I don't want to use try
and catch
to circumvent the error or to somehow check if the variable exists before I use alert()
. I know and want the error to happen, I just want to prevent its display. I hope that makes this more clear.
When you run this, the console.log function is never actually called. The alert function fails, logs that it failed, and the click listener function exits. console.log()
is never reached. This means you just need to stop the alert from showing an error. This is where try catch statements are helpful.
$("#fix-this-error").click(function () {
try {
alert(this_should_not_show_up_in_the_console);
console.log("This won't show");
} catch (e) {
// Code jumps here when `alert()` fails.
// `e` stores information about the error
// If you don't want to put everything in the try/catch,
// you can stop the function from continuing execution with
return;
}
});