|
|
|
|
|
by theamk
950 days ago
|
|
I think it's kinda the opposite actually... with go, you have to go out of the way to generate those errors, while in Python, most of this is automatic. In particular, the ReadFile example in Python will raise OSError, and those already include filename and error message. So you'd get the same result with 0 extra lines. For the second example, the json unmarshalling will not auto-add filename, but its easy enough to do using exception chaining: try:
data = json.loads(bytes)
process_1(data)
process_2(data)
except:
raise Exception(f"Error while parsing file {filename}")
which will give stacktrace like: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "somefile.py", line 4, in somefile
Exception: Failed while parsing file.json
Note that's even more detailed than go, with significantly less boilerplate (only 3 lines per function) vs 3 lines per call.(an anecdote: we've had the team which converted the CLI tool from Python to Golang. The first time they ran the tool, it printed a single line: invalid character '"' after top-level value
and that's it. It took a lot of debugging before they could figure out what happened. All because they got used to python doing super-rich traceback automatically, with 0 effort from programmers) |
|
I accept it's largely personal preference, but having used both mechanisms for many years, I find Go best practices for error handling are simple and easy to follow, and results in easily maintainable code, compared to exception handling which doesn't really come with a simple set of best practices, meaning it is often badly put together or added as an afterthought.