32
loading...
This website collects cookies to deliver better user experience
This is Day 15 of the #100DaysOfPython challenge.
hello-python-exceptions
directory and install Pillow.# Make the `hello-python-exceptions` directory
$ mkdir hello-python-exceptions
$ cd hello-python-exceptions
# Init the virtual environment
$ pipenv --three
$ pipenv install --dev jupyterlab
# Startup the notebook server
$ pipenv run jupyter-lab
# ... Server is now running on http://localhost:8888/lab
hello-python-exceptions/docs/<your-file-name>
.try/except
works.try/except
statement to handle errors. You raise
an Exception
whenever you want to throw an error from a code block.Exception
is self can then be delegated higher up the code chain to be handled.try:
raise Exception('You shall not pass')
print('Success')
except:
print('There was an issue')
There was an issue
. We do not make it passed the raised exception.try:
raise Exception('You shall not pass')
print('Success')
except Exception:
print('Did not make it to final catch-all block')
except:
print('There was an issue')
'Did not make it to final catch-all block'
was captured and printed, where as the final except
code block is used a capture all.def example_exception():
raise Exception('You shall not pass')
def example_fn():
example_exception()
try:
example_fn()
except:
print('There was an issue')
'There was an issue'
.Exception
.class CustomError(Exception):
"""Custom error"""
pass
randrange
function as a helper to determine which error to raise:from random import randrange
# define Python user-defined exceptions
class CustomError(Exception):
"""Raised when using a custom error"""
pass
def example_exception():
val = randrange(10)
if val <= 5:
raise CustomError('You shall not pass')
else:
raise Exception("There was an error")
try:
example_exception()
except CustomError as e:
print(e)
except Exception as e:
print(e)
'You shall not pass'
or 'There was an error'
based on the random value.CustomError
is being handled in the except CustomError as e
block.Exception
and demonstrating how errors are raised in a simple manner.freestocks