[Python-ideas] Arguments to exceptions
Steven D'Aprano
steve at pearwood.info
Tue Jul 4 10:37:54 EDT 2017
On Mon, Jul 03, 2017 at 01:46:14PM -0600, Jeff Walker wrote:
> Consider this example:
>
> import json
>
> >>> s = '{"abc": 0, "cdf: 1}'
>
> >>> try:
> ... d = json.loads(s)
> ... except Exception as e:
> ... print(e)
> ... print(e.args)
> Unterminated string starting at: line 1 column 12 (char 11)
> ('Unterminated string starting at: line 1 column 12 (char 11)',)
>
> Okay, I have caught an exception for which I have no control over how the
> exception was raised. Now, imagine that I am writing an application that highlights
> json errors in place. To do so, I would need the line and column numbers to
> highlight the location of the error, and ideally I'd like to strip them from the base
> message and just show that.
I disagree: you should be using a JSON library which offers the line and
column number as part of its guaranteed, supported API for dealing with
bad JSON. If those numbers aren't part of the library API, then it is
just as much of a fragile hack to extract them from exception.args[] as
to scrape them from the error message.
Suppose you write this:
print(err.args)
which gives:
[35, 42, 'Unterminated string starting at: line 42 column 36']
Without parsing the error string, how do you know whether 35 is the line
number or the column number or the character offset or something else
that you didn't think of?
Even when the information is there, in the exception args, it is still a
fragile hack to extract them if they aren't part of the API.
> I don't know what this code smell is that people keep referring to, but to me,
> that code would smell.
https://www.martinfowler.com/bliki/CodeSmell.html
--
Steve
More information about the Python-ideas
mailing list