I had a piece of code my professor commented on, saying that "this is called a squelch" and that it's a huge sin in programming.
Here's the code I had,
if (command.matches(input)) {
try {
command.execute();
} catch (UniversalException e) {
}
return;
}
The "squelch" was within the catch(). I have kind of an idea from research what this is, but if someone could explain it to me in simpler terms, I'd appreciate it. Also how to avoid a squelch would be nice, too.
Also, if it helps, that bit of code also includes
public UniversalException() {
System.out.println("The file you entered could not be located. Please try again.");
}
in another class, which is what is printed out when a user enters an invalid file name.
I don't understand any of this exception stuff well yet, and my professor simply asked for something that prints out a nice message to the user instead of a stack trace.
That's a funny, if descriptive name for it :)
If I'm not misinterpreting what your professor said, the problem is that inside your 'catch' block, you do absolutely nothing. You don't print a nice error message, you don't log the error, you don't throw the exception so that somebody else can handle it, you don't show the stack trace...
If the code inside the try block were to throw a UniversalException, your empty catch block would cause that error to be silently ignored, suppressed, or squelched.
The solution is fairly simple -- do something inside the catch block. Errors should never be silently ignored -- at minimum, you should at least print or log something so that you know something went wrong.
Now, currently, it looks like you're actually printing an error message in the constructor of the UniversalException
class. I would instead move that into the catch block. An empty catch block feels sort of like a fly walking across your arm -- it just feels wrong, even if you do log the error somewhere else.
The reason why many coders have this sort of instinctual revulsion to empty catch blocks is because it usually indicates a landmine. Whenever I see an empty catch block, it usually means that the previous coder deliberately chose to ignore an error in the code and hope for the best, which is almost never the right thing to do. It's not the kind of thing that makes you optimistic about the state of the codebase.
It's also more useful to print the error message inside the catch block instead of in the constructor since you can also print out the values of local variables in the method and examine the specific exception thrown, which makes it easier to debug the problem.
Your code catches an exception (in this case, an instance of UniversalException
) and does not act upon it. This way, since the exception is neither allowed to propagate "upwards" nor is it handled in any way, you are effectively hiding the fact that it ever occurred.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With