-
-
Notifications
You must be signed in to change notification settings - Fork 313
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Checks: Fix E722 do not use bare except
#3748
base: main
Are you sure you want to change the base?
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Great. except Exception
is far better than bare except
which catches even syntax errors, but later we will aim at Pylint and that asks for something more specific than Exception.
It seems easier to see the exceptions here in this PR than going to Pylint later on, so fixing as much as possible now would be good.
Nevertheless, I would aim at the clear cases in this PR. I tried to mark couple of cases which are clear and will be repeated over several files. Ultimately, you need to look at every case. If you need to read more than 10 lines of code to understand the context, leaving Exception is probably the right choice.
scripts/r.in.wms/wms_gdal_drv.py
Outdated
try: | ||
from osgeo import gdal | ||
except: | ||
except Exception: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Cases like this are import error.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
except ImportError:
scripts/r.in.wms/srs.py
Outdated
try: | ||
self.code = int(values[-1]) | ||
except: | ||
except Exception: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is a case where code context helps: values clearly has at least one value, so the indexing will succeed here. What can fail is the conversion to an integer.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
except ValueError:
scripts/r.in.srtm/r.in.srtm.py
Outdated
try: | ||
grass.run_command("r.in.gdal", input=bilfile, out=tileout) | ||
except: | ||
except Exception: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The provided error message is trivial. This will be better handled by removing try-except and simply asking run_command to issue the fatal error with errors="fatal"
:
run_command(..., errors="fatal")
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What about grass.read_command
? It appears that it works with the "errors" parameter. A question would be the status of the errors. For example, gui/wxpython/core/utils.py
def _getGDALFormats():
"""Get dictionary of available GDAL drivers"""
try:
ret = grass.read_command("r.in.gdal", quiet=True, flags="f")
except Exception:
ret = None
return _parseFormats(ret), _parseFormats(ret, writableOnly=True)
def _getOGRFormats():
"""Get dictionary of available OGR drivers"""
try:
ret = grass.read_command("v.in.ogr", quiet=True, flags="f")
except Exception:
ret = None
return _parseFormats(ret), _parseFormats(ret, writableOnly=True)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That should be grass.exceptions.CalledModuleError
:
https://grass.osgeo.org/grass84/manuals/libpython/grass.exceptions.html#grass.exceptions.CalledModuleError
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Note: The difference here is gui/wxpython/
versus a scripts/
.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm reading the code between try
and except
and finding possible errors, so you may want to disregard some of the errors I listed in except
. As a side note, I used code assistant to find out some of the most common exceptions, and then evaluated whether they might occur in the given code.
Third-party library exceptions (e.g. wxPython) and nested internal function calls related exceptions are difficult to figure out. In such a situation, broad exceptions are useful, so I kept them as they are, but please let me know if you have any suggestions for specific exceptions.
gui/wxpython/core/gconsole.py
Outdated
@@ -676,7 +676,7 @@ def RunCmd( | |||
if len(command) == 1 and not skipInterface: | |||
try: | |||
task = gtask.parse_interface(command[0]) | |||
except: | |||
except Exception: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I wanted to note any changes I made along the way.
parse_interface
from grass.exceptions import ScriptError
except ScriptError:
gui/wxpython/core/render.py
Outdated
@@ -1242,7 +1242,7 @@ def SetRegion(self, windres=False, windres3=False): | |||
|
|||
return grass_region | |||
|
|||
except: | |||
except Exception: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
except (KeyError, TypeError):
gui/wxpython/core/settings.py
Outdated
@@ -110,7 +110,7 @@ def _generateLocale(self): | |||
self.locs.sort() | |||
# Add a default choice to not override system locale | |||
self.locs.insert(0, "system") | |||
except: | |||
except Exception: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
except (KeyError, FileNotFoundError, PermissionError, NotADirectoryError, OSError):
- KeyError: This would occur if the environment variable "GISBASE" is not set.
- FileNotFoundError: This would be raised by os.listdir() if the directory specified does not exist. In this case, if the "locale" directory does not exist within the directory specified by "GISBASE".
- PermissionError: This would be raised by os.listdir() if the user does not have the necessary permissions to read the contents of the directory.
- NotADirectoryError: This would be raised by os.listdir() if the path exists but is not a directory.
- OSError: This would be raised by os.listdir() for reasons like insufficient system resources or other OS-related issues.
gui/wxpython/core/settings.py
Outdated
@@ -992,7 +992,7 @@ def SaveToFile(self, settings=None): | |||
if not os.path.exists(dirPath): | |||
try: | |||
os.mkdir(dirPath) | |||
except: | |||
except Exception: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
except OSError:
scripts/v.unpack/v.unpack.py
Outdated
@@ -77,7 +77,7 @@ def main(): | |||
tar = tarfile.TarFile.open(name=input_base, mode="r") | |||
try: | |||
data_name = tar.getnames()[0] | |||
except: | |||
except Exception: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
except (AttributeError, IndexError, tarfile.ReadError):
- AttributeError: This exception is raised if the tar object does not have a getnames method. This could occur if tar is not a TarFile object.
- IndexError: This exception is raised during the tar.getnames()[0] call if the result of tar.getnames() does not have at least one element. This could occur if the tar file is empty.
- tarfile.ReadError: This exception is raised if the tar file cannot be read, which might happen if the file is not a tar file or is corrupted.
utils/gitlog2changelog.py
Outdated
@@ -66,7 +66,7 @@ | |||
author = authorList[1] | |||
author = author[0 : len(author) - 1] | |||
authorFound = True | |||
except: | |||
except Exception: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
except IndexError:
utils/gitlog2changelog.py
Outdated
@@ -76,7 +76,7 @@ | |||
date = dateList[1] | |||
date = date[0 : len(date) - 1] | |||
dateFound = True | |||
except: | |||
except Exception: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
except (IndexError, TypeError):
@@ -118,31 +118,31 @@ def get_number_of_spatial_relations(self): | |||
relations = {} | |||
try: | |||
relations["equivalent"] = len(self._spatial_topology["EQUIVALENT"]) | |||
except: | |||
except (KeyError, TypeError): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The class, e.g., def append_equivalent(self, map):
, always creates the dict item with an empty list, so the len
call should always succeed, so there should be no TypeError, or if there is, it is programmer's fault and traceback is the desired behavior.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Keeping except Exception
for now?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I meant the opposite. If you analyze the code, it should reveal that of the dict item is there, it will be an empty list. So, no TypeError. The attribute seems to be present. (Please check.) This would leave KeyError as what the original author intended to catch here.
scripts/v.unpack/v.unpack.py
Outdated
except (AttributeError, IndexError, tarfile.ReadError): | ||
grass.fatal(_("Pack file unreadable")) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Same as the other extract code: Report the error to the user.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I am guessing you are refering to scripts/r.in.srtm/r.in.srtm.py
and changed to as following.
except (AttributeError, IndexError, tarfile.ReadError) as error:
grass.fatal(_("Pack file unreadable: {error}").format(error=error))
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Did you push the change?
utils/gitlog2changelog.py
Outdated
@@ -76,7 +76,7 @@ | |||
date = dateList[1] | |||
date = date[0 : len(date) - 1] | |||
dateFound = True | |||
except: | |||
except (IndexError, TypeError): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why TypeError?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
TypeError: This will occur if dateList is not a list or if dateList[1] is not a string. This can happen if the input to this code snippet is not as expected.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
dateList and dateList[1] are a result of the re.split function call on line 74 which returns a list of strings according to the documentation.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I left comments for several changes. Some of them hopefully apply generally, too.
scripts/r.in.srtm/r.in.srtm.py
Outdated
@@ -230,8 +230,8 @@ def main(): | |||
try: | |||
zf = zfile.ZipFile(zipfile) | |||
zf.extractall() | |||
except: | |||
grass.fatal(_("Unable to unzip file.")) | |||
except (FileNotFoundError, PermissionError, OSError, zipfile.BadZipFile) as error: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[black] reported by reviewdog 🐶
except (FileNotFoundError, PermissionError, OSError, zipfile.BadZipFile) as error: | |
except ( | |
FileNotFoundError, | |
PermissionError, | |
OSError, | |
zipfile.BadZipFile, | |
) as error: |
lib/init/grass.py
Outdated
@@ -2213,7 +2213,7 @@ def print_params(params): | |||
try: | |||
revision = linerev.split(" ")[1] | |||
sys.stdout.write("%s\n" % revision[1:]) | |||
except: | |||
except (IndexError, TypeError, AttributeError): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
AttributeError - Generally, attribute error should not be caught unless there is a specific reason to do so (like dealing with different types of objects and reacting to the differences in their attributes).
TypeError - Where this would happen and is that something we want to hide or cause traceback?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
TypeError happens as following.
TypeError: This exception could be raised by revision[1:] if revision is not a string or bytes-like object. The slicing operation is not supported by all data types, so if revision is not of a type that supports slicing, a TypeError would be raised.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Under which conditions revision would not be a string? The revision value is a result of the line 2214 which splits a string using str.split which returns list of the words in the string.
Fixed conflicts, maybe some changes wouldn't still be needed since some work has already been done (and those lines would revert back if I didn't do my job correctly) |
Solved conflicts. The diff is now smaller, as multiple issues where already fixed |
@arohanajit Before you finish the year, can you take a look at what's left here? |
The entire fix involves converting
except:
intoexcept Exception:
. Please let me know if specific exceptions are needed in certain conditions.