Skip to content

Commit 425c172

Browse files
committed
else clauses can be really nice
thought you might want to add in this nice insight about `else` clauses in exception handling
1 parent 626ff20 commit 425c172

1 file changed

Lines changed: 9 additions & 3 deletions

File tree

exceptions.rst

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -89,8 +89,11 @@ to perform clean-up after a script. Here is a simple example:
8989
~~~~~~~~~~~~~~~~~~~
9090

9191
Often times we might want some code to run if **no** exception occurs. This
92-
can easily be achieved by using an ``else`` clause. Most people don't
93-
use it and honestly I have myself not used it widely. Here is an
92+
can easily be achieved by using an ``else`` clause. One might ask: why, if
93+
you only want some code to run if no exception occurs, wouldn't you simply
94+
put that code inside the ``try``? The answer is that then any exceptions in
95+
that code will be caught by the ``try``, and you might not want that. Most
96+
people don't use it and honestly I have myself not used it widely. Here is an
9497
example:
9598

9699
.. code:: python
@@ -100,7 +103,10 @@ example:
100103
except Exception:
101104
print('exception')
102105
else:
103-
print('This would only run if no exception occurs.')
106+
# any code that should only run if no exception occurs in the try,
107+
# but for which exceptions should NOT be caught
108+
print('This would only run if no exception occurs. And an error here '
109+
'would NOT be caught.')
104110
finally:
105111
print('This would be printed in every case.')
106112

0 commit comments

Comments
 (0)