Be a little more strict about what exceptions are caught. #2
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
I've been burned many times by having a bare except clause vacuum up any old exceptions. In particular, your commit had the following code:
There are 4 different lines of code after opening the logfile that get executed, 3 of which could raise an exception. Someone could mask the datetime module with their own by accident, raising an
AttributeError
that gets caught as an apparent permissions error. I could accidentally change theparmed_commands.setlog
API that would raise any of a number of errors.Or maybe I use a binary file open function to open opt.logfile (maybe BZ2File or GzipFile) but forget to encode the logfile text. It works fine in Python 2, but then raises a TypeError due to the bytes/str split in Python 3 that appears to users as some kind of permissions error. All of these could mask what's really happening and make whatever bug that comes out of it very difficult to find.
There are times to use a bare except -- usually if you want to print something before re-raising the exception (I use one in ParmEd in the format registry metaclass for a very specific reason, but that one instance has caused problems like I described above). In general, though, you should execute as few functions in the
try
block as possible (use thetry: ... except: ... else:
block like I did here instead), and catch specific exceptions (can be multiple specific exception types). This will minimize the chances that you are masking errors and can make your life much easier when hunting certain bugs.The only reason I bring this up and make a big deal of it is because I know you are writing your own program in pytraj, and adopting practices like the above has saved me lots of time compared to the time when I used to use bare excepts.
BTW, once you merge this PR into your branch, it will update to your PR and I can merge it. Thanks for the fix!