Skip to content

Commit 40d7449

Browse files
committed
Fix exception causes all over the codebase
1 parent fe34774 commit 40d7449

24 files changed

+84
-75
lines changed

doc/sphinxext/github.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,8 @@ def make_link_node(rawtext, app, type, slug, options):
3939
base += '/'
4040
except AttributeError as err:
4141
raise ValueError(
42-
f'github_project_url configuration value is not set ({err})')
42+
f'github_project_url configuration value is not set '
43+
f'({err})') from err
4344

4445
ref = base + type + '/' + slug + '/'
4546
set_classes(options)
@@ -137,7 +138,8 @@ def ghcommit_role(
137138
base += '/'
138139
except AttributeError as err:
139140
raise ValueError(
140-
f'github_project_url configuration value is not set ({err})')
141+
f'github_project_url configuration value is not set '
142+
f'({err})') from err
141143

142144
ref = base + text
143145
node = nodes.reference(rawtext, text[:6], refuri=ref, **options)

examples/user_interfaces/embedding_webagg_sgskip.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@
1616

1717
try:
1818
import tornado
19-
except ImportError:
20-
raise RuntimeError("This example requires tornado.")
19+
except ImportError as err:
20+
raise RuntimeError("This example requires tornado.") from err
2121
import tornado.web
2222
import tornado.httpserver
2323
import tornado.ioloop

lib/matplotlib/__init__.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -656,10 +656,10 @@ def __setitem__(self, key, val):
656656
except ValueError as ve:
657657
raise ValueError(f"Key {key}: {ve}") from None
658658
dict.__setitem__(self, key, cval)
659-
except KeyError:
659+
except KeyError as err:
660660
raise KeyError(
661661
f"{key} is not a valid rc parameter (see rcParams.keys() for "
662-
f"a list of valid parameters)")
662+
f"a list of valid parameters)") from err
663663

664664
def __getitem__(self, key):
665665
if key in _deprecated_map:
@@ -942,9 +942,9 @@ def rc(group, **kwargs):
942942
key = '%s.%s' % (g, name)
943943
try:
944944
rcParams[key] = v
945-
except KeyError:
945+
except KeyError as err:
946946
raise KeyError(('Unrecognized key "%s" for group "%s" and '
947-
'name "%s"') % (key, g, name))
947+
'name "%s"') % (key, g, name)) from err
948948

949949

950950
def rcdefaults():

lib/matplotlib/axes/_axes.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4210,11 +4210,11 @@ def _parse_scatter_color_args(c, edgecolors, kwargs, xsize,
42104210
if kwcolor is not None:
42114211
try:
42124212
mcolors.to_rgba_array(kwcolor)
4213-
except ValueError:
4213+
except ValueError as err:
42144214
raise ValueError(
42154215
"'color' kwarg must be an color or sequence of color "
42164216
"specs. For a sequence of values to be color-mapped, use "
4217-
"the 'c' argument instead.")
4217+
"the 'c' argument instead.") from err
42184218
if edgecolors is None:
42194219
edgecolors = kwcolor
42204220
if facecolors is None:
@@ -4264,14 +4264,14 @@ def invalid_shape_exception(csize, xsize):
42644264
if not c_is_mapped:
42654265
try: # Is 'c' acceptable as PathCollection facecolors?
42664266
colors = mcolors.to_rgba_array(c)
4267-
except (TypeError, ValueError):
4267+
except (TypeError, ValueError) as err:
42684268
if not valid_shape:
4269-
raise invalid_shape_exception(c.size, xsize)
4269+
raise invalid_shape_exception(c.size, xsize) from err
42704270
# Both the mapping *and* the RGBA conversion failed: pretty
42714271
# severe failure => one may appreciate a verbose feedback.
42724272
raise ValueError(
42734273
f"'c' argument must be a color, a sequence of colors, or "
4274-
f"a sequence of numbers, not {c}")
4274+
f"a sequence of numbers, not {c}") from err
42754275
else:
42764276
if len(colors) not in (0, 1, xsize):
42774277
# NB: remember that a single color is also acceptable.

lib/matplotlib/axes/_base.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1732,10 +1732,10 @@ def axis(self, *args, emit=True, **kwargs):
17321732
limits = args[0]
17331733
try:
17341734
xmin, xmax, ymin, ymax = limits
1735-
except (TypeError, ValueError):
1735+
except (TypeError, ValueError) as err:
17361736
raise TypeError('the first argument to axis() must be an '
17371737
'interable of the form '
1738-
'[xmin, xmax, ymin, ymax]')
1738+
'[xmin, xmax, ymin, ymax]') from err
17391739
else:
17401740
xmin = kwargs.pop('xmin', None)
17411741
xmax = kwargs.pop('xmax', None)
@@ -2885,8 +2885,9 @@ def ticklabel_format(self, *, axis='both', style='', scilimits=None,
28852885
try:
28862886
m, n = scilimits
28872887
m + n + 1 # check that both are numbers
2888-
except (ValueError, TypeError):
2889-
raise ValueError("scilimits must be a sequence of 2 integers")
2888+
except (ValueError, TypeError) as err:
2889+
raise ValueError("scilimits must be a sequence of 2 integers"
2890+
) from err
28902891
STYLES = {'sci': True, 'scientific': True, 'plain': False, '': None}
28912892
is_sci_style = cbook._check_getitem(STYLES, style=style)
28922893
axis_map = {**{k: [v] for k, v in self._get_axis_map().items()},
@@ -2904,9 +2905,9 @@ def ticklabel_format(self, *, axis='both', style='', scilimits=None,
29042905
axis.major.formatter.set_useLocale(useLocale)
29052906
if useMathText is not None:
29062907
axis.major.formatter.set_useMathText(useMathText)
2907-
except AttributeError:
2908+
except AttributeError as err:
29082909
raise AttributeError(
2909-
"This method only works with the ScalarFormatter")
2910+
"This method only works with the ScalarFormatter") from err
29102911

29112912
def locator_params(self, axis='both', tight=None, **kwargs):
29122913
"""

lib/matplotlib/backends/backend_agg.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -143,15 +143,16 @@ def draw_path(self, gc, path, transform, rgbFace=None):
143143
p = Path(v, c)
144144
try:
145145
self._renderer.draw_path(gc, p, transform, rgbFace)
146-
except OverflowError:
147-
raise OverflowError("Exceeded cell block limit (set "
148-
"'agg.path.chunksize' rcparam)")
146+
except OverflowError as err:
147+
raise OverflowError(
148+
"Exceeded cell block limit (set 'agg.path.chunksize' "
149+
"rcparam)") from err
149150
else:
150151
try:
151152
self._renderer.draw_path(gc, path, transform, rgbFace)
152-
except OverflowError:
153+
except OverflowError as err:
153154
raise OverflowError("Exceeded cell block limit (set "
154-
"'agg.path.chunksize' rcparam)")
155+
"'agg.path.chunksize' rcparam)") from err
155156

156157
def draw_mathtext(self, gc, x, y, s, prop, angle):
157158
"""Draw mathtext using :mod:`matplotlib.mathtext`."""

lib/matplotlib/backends/backend_cairo.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,10 @@
1818
except ImportError:
1919
try:
2020
import cairocffi as cairo
21-
except ImportError:
21+
except ImportError as err:
2222
raise ImportError(
2323
"cairo backend requires that pycairo>=1.11.0 or cairocffi"
24-
"is installed")
24+
"is installed") from err
2525

2626
from .. import cbook
2727
from matplotlib.backend_bases import (

lib/matplotlib/backends/backend_gtk3.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@
1616

1717
try:
1818
import gi
19-
except ImportError:
20-
raise ImportError("The GTK3 backends require PyGObject")
19+
except ImportError as err:
20+
raise ImportError("The GTK3 backends require PyGObject") from err
2121

2222
try:
2323
# :raises ValueError: If module/version is already loaded, already
@@ -47,7 +47,7 @@
4747
except TypeError as exc:
4848
# Happens when running headless. Convert to ImportError to cooperate with
4949
# backend switching.
50-
raise ImportError(exc)
50+
raise ImportError(exc) from exc
5151

5252

5353
class TimerGTK3(TimerBase):

lib/matplotlib/backends/backend_nbagg.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -164,9 +164,10 @@ def __init__(self, manager):
164164
display(HTML("<div id=%r></div>" % self.uuid))
165165
try:
166166
self.comm = Comm('matplotlib', data={'id': self.uuid})
167-
except AttributeError:
167+
except AttributeError as err:
168168
raise RuntimeError('Unable to create an IPython notebook Comm '
169-
'instance. Are you in the IPython notebook?')
169+
'instance. Are you in the IPython '
170+
'notebook?') from err
170171
self.comm.on_msg(self.on_message)
171172

172173
manager = self.manager

lib/matplotlib/backends/backend_pgf.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -273,13 +273,14 @@ def __init__(self):
273273
[self.texcommand, "-halt-on-error"],
274274
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
275275
encoding="utf-8", cwd=self.tmpdir)
276-
except FileNotFoundError:
276+
except FileNotFoundError as err:
277277
raise RuntimeError(
278278
f"{self.texcommand} not found. Install it or change "
279279
f"rcParams['pgf.texsystem'] to an available TeX "
280-
f"implementation.")
281-
except OSError:
282-
raise RuntimeError("Error starting process %r" % self.texcommand)
280+
f"implementation.") from err
281+
except OSError as err:
282+
raise RuntimeError("Error starting process %r" %
283+
self.texcommand) from err
283284
test_input = self.latex_header + latex_end
284285
stdout, stderr = latex.communicate(test_input)
285286
if latex.returncode != 0:
@@ -342,7 +343,7 @@ def get_width_height_descent(self, text, prop):
342343
self._expect_prompt()
343344
except LatexError as e:
344345
raise ValueError("Error processing '{}'\nLaTeX Output:\n{}"
345-
.format(text, e.latex_output))
346+
.format(text, e.latex_output)) from e
346347

347348
# typeout width, height and text offset of the last textbox
348349
self._stdin_writeln(r"\typeout{\the\wd0,\the\ht0,\the\dp0}")
@@ -351,14 +352,14 @@ def get_width_height_descent(self, text, prop):
351352
answer = self._expect_prompt()
352353
except LatexError as e:
353354
raise ValueError("Error processing '{}'\nLaTeX Output:\n{}"
354-
.format(text, e.latex_output))
355+
.format(text, e.latex_output)) from e
355356

356357
# parse metrics from the answer string
357358
try:
358359
width, height, offset = answer.splitlines()[0].split(",")
359-
except Exception:
360+
except Exception as err:
360361
raise ValueError("Error processing '{}'\nLaTeX Output:\n{}"
361-
.format(text, answer))
362+
.format(text, answer)) from err
362363
w, h, o = float(width[:-2]), float(height[:-2]), float(offset[:-2])
363364

364365
# the height returned from LaTeX goes from base to top.

0 commit comments

Comments
 (0)