Skip to Content
Learn Python by Building Data Science Applications
book

Learn Python by Building Data Science Applications

by Philipp Kats, David Katz
August 2019
Beginner
482 pages
12h 56m
English
Packt Publishing
Content preview from Learn Python by Building Data Science Applications

try/except

The try/except construct allows you to handle the errors within and fall back on alternative code if something goes wrong. You can use it for an exception as an umbrella case (any error), or specify precise exceptions to catch. In the following code, we're trying to run a bad code, dividing by zero. In this case, Python raises a specific exception—ZeroDivisionError. Knowing that, we add an except ZeroDivisionError clause, printing a string in it:

>>> try:>>>     result = 1 / 0>>> except ZeroDivisionError:>>>     print('something is wrong!')something is wrong!

Because we are catching specific ZeroDivisionError exceptions, everything else will still raise an exception. As it is precisely the exception that was raised, we caught it, a

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python for Data Science

Python for Data Science

Yuli Vasiliev
Introduction to Machine Learning with Python

Introduction to Machine Learning with Python

Andreas C. Müller, Sarah Guido

Publisher Resources

ISBN: 9781789535365Supplemental Content