[Tutor] try, except syntax

Oscar Benjamin oscar.j.benjamin at gmail.com
Thu Aug 2 14:57:23 EDT 2018


On 2 August 2018 at 15:29, Shall, Sydney <sydney.shall at kcl.ac.uk> wrote:
>
> try:
>     type(uvc) == float
> except TypeError as e:
>     print(e, msg)

Let's try this interactively:

>>> uvc = 2
>>> type(uvc)
<class 'int'>
>>> type(uvc) == float
False

So calling type(uvc) doesn't raise an error. It returns the type
"int". You then compare this with the type "float" and they are not
equal so the comparison results in False. No exception is raised by
this code because there hasn't been an error anywhere. If no exception
is raised then you cannot catch an exception with try/except.

You should use try/except around some code that would raise an
exception if given the wrong sort of input e.g.:

numstring = input('Enter a number')
try:
    number = int(numstring)
except ValueError:
    print('Not a decimal number: %r' % numstring)

In your case do you even need to do this type check? If you're
catching the exception then you could also just not catch the
exception so that the user sees the error message. The answer to this
depends on what kind of user you have. If a user isn't directly
touching the code then it shouldn't be possible for them to change the
type of uvc so this exception won't occur and you don't need to check
for it. If the user is both editing and running the code (e.g. if you
are the only user) then it's usually okay to let them see the normal
error message that Python will print out so again you don't need to
check for it.

On the other hand if the user does something that won't *already* lead
to an exception but would result in your code doing something
meaningless (such as giving a negative number) then that is a good
time for you to check something and raise an exception yourself.

--
Oscar


More information about the Tutor mailing list