The Python Apprentice by Robert Smallshire & Austin Bingham
Author:Robert Smallshire & Austin Bingham [Smallshire, Robert]
Language: eng
Format: azw3, epub
Publisher: Packt Publishing
Published: 2017-06-21T04:00:00+00:00
Handling exceptions
Let's make our convert() function more robust by handling the ValueError using a try … except construct. Both the try and except keywords introduce new blocks. The try block contains code that could raise an exception and the except block contains the code which performs error handling in the event that an exception is raised. Modify the convert() function to look like this:
def convert(s):
"""Convert a string to an integer."""
try:
x = int(s)
except ValueError:
x = -1
return x
We have decided that if a non-integer string is supplied, we'll return minus one. To reinforce your understanding of the control-flow here we'll also add a couple of print statements:
def convert(s):
"""Convert a string to an integer."""
try:
x = int(s)
print("Conversion succeeded! x =", x)
except ValueError:
print("Conversion failed!")
x = -1
return x
Let's test this interactively after restarting the REPL:
>>> from exceptional import convert
>>> convert("34")
Conversion succeeded! x = 34
34
>>> convert("giraffe")
Conversion failed!
-1
Note how the print() in the try block after the point at which the exception was raised was not executed when we passed in "giraffe" as the function argument. Instead, execution was transferred directly to the first statement of the except block.
The int() constructor only accepts numbers or strings, so let's see what happens if we feed an object of another type into it, say a list:
>>> convert([4, 6, 5])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "./exceptional.py", line 8, in convert
x = int(s)
TypeError: int() argument must be a string or a number, not 'list'
This time our handler didn't intercept the exception. If we look closely at the trace, we can see that this time we received a TypeError – a different type of exception.
Download
The Python Apprentice by Robert Smallshire & Austin Bingham.epub
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.
Hello! Python by Anthony Briggs(9914)
OCA Java SE 8 Programmer I Certification Guide by Mala Gupta(9796)
The Mikado Method by Ola Ellnestam Daniel Brolund(9777)
Algorithms of the Intelligent Web by Haralambos Marmanis;Dmitry Babenko(8296)
Sass and Compass in Action by Wynn Netherland Nathan Weizenbaum Chris Eppstein Brandon Mathis(7778)
Test-Driven iOS Development with Swift 4 by Dominik Hauser(7763)
Grails in Action by Glen Smith Peter Ledbrook(7696)
The Well-Grounded Java Developer by Benjamin J. Evans Martijn Verburg(7557)
Windows APT Warfare by Sheng-Hao Ma(6835)
Layered Design for Ruby on Rails Applications by Vladimir Dementyev(6565)
Blueprints Visual Scripting for Unreal Engine 5 - Third Edition by Marcos Romero & Brenden Sewell(6431)
Secrets of the JavaScript Ninja by John Resig Bear Bibeault(6413)
Kotlin in Action by Dmitry Jemerov(5062)
Hands-On Full-Stack Web Development with GraphQL and React by Sebastian Grebe(4316)
Functional Programming in JavaScript by Mantyla Dan(4038)
Solidity Programming Essentials by Ritesh Modi(3999)
WordPress Plugin Development Cookbook by Yannick Lefebvre(3790)
Unity 3D Game Development by Anthony Davis & Travis Baptiste & Russell Craig & Ryan Stunkel(3735)
The Ultimate iOS Interview Playbook by Avi Tsadok(3710)
