For example, is it considered bad practice to write:
try
{
#some code
}
catch (Exception e){
#some code
}
Rather than
try
{
#some code
}
catch (ExceptionName e){ #like ArrayIndexOutOfBoundsException
#some code
}
I guess the question holds for pretty much every language, be it Python, C++, Java...Any thoughts?
I am asking because it seems to me that you shouldn't, since it means you don't know what kind of error you are handling and what to do with it, but I see some people do it.
YES!
There is a single exception to this:
You want to catch, do something, then re-throw. Maybe you have some resources you need to close before the exception goes up, or you want to inform the user something wrong has happened:
FileResource fileResource = new FileResource("/some/path");
try {
fileResource.open();
fileResource.dostuff();
//other logic
} catch (Exception e){
fileResource.close();
throw e;
}
Hence, when an exception gets thrown, you can close your resources before the program exits.
Always catch the most specific exception type you can.
Also, catching all Exceptions is exceptionally bad in Python, because you can catch syntax exceptions and the like.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments