[Tutor] try, except syntax

Marc Tompkins marc.tompkins at gmail.com
Thu Aug 2 15:19:41 EDT 2018


try... except is meant to catch errors: places where your program would
otherwise crash.  It does NOT work as a truth check.
In your example:

> try:
>     type(uvc) == float
> except TypeError as e:
>     print(e, msg)
>
> "type(uvc)==float" resolves to a standalone True or False, not an
exception.  What you want in that case is an assertion:

>   try:
>       assert type(uvc)==float
>   except AssertionError as e:
>       print(e, msg)


An assertion says "The following statement is True.  If it isn't, I'm going
to throw an exception."  They're especially useful when writing tests, and
should be part of your flow-control toolbox.

In your last two examples,

> if type(uvc) != float:
>     raise TypeError("Bad argument provided. And this is also old test."
>                     " The value of UVC must be a float. This is old test")
> if uvc < 0.0 or uvc > 1.0:
>     raise ValueError("Bad argument provided. The value of uvc must be "
>                      "greater than 0.0 and less than 1.0. This is old
> test")


I assume you must either already be using try/except, or else never getting
incorrect input; if you raise an exception but don't catch it, the program
terminates.  I would wrap those thusly:

> try:
>   if type(uvc) != float:
>       raise TypeError("Bad argument provided. And this is also old test."
>                       " The value of UVC must be a float. This is old
> test")
>   if uvc < 0.0 or uvc > 1.0:
>       raise ValueError("Bad argument provided. The value of uvc must be "
>                        "greater than 0.0 and less than 1.0. This is old
> test")
> except Error as e:
>   print(e,msg)


Generally, however, my approach is to use if/then for normal program flow,
and wrap those in try/except for cases where e.g. user error may cause
crashes.


More information about the Tutor mailing list