Another basic language feature I'll cover in this tutorial is exception handling (which I wrote about in Kotlin a few days ago.
Traditionally, I'll show some examples. Let's begin with simple code, asking user for two numbers and dividing them. Of course, such program may encounter probably the most basic exception: division by 0. But also another one: if we put something not being a number, it cannot be converted to float and some other exception would be expected.
First, the code without any exeption handling would look like this:
We create a function divide(a, b) , returning division result. Then we get two numbers from user, a and b using input('... ') function and converting them to float using float() function (as input('a = ') returns simply a string).
If given two numbers which we can divide by eachother, the result is not surprising:
But if we put 0 as b...
... we get a cute stacktrace. Well, division by 0 is not possible, and therefore results in an exception. Quite obvious :)
Before we try to deal with this proble, let's put another strange data as input to program: try to divide 10 by horse. Well, this also shouldn't be possible, right?
... as expected. Of course, here another exception is caught (and in other place: not when trying to divide, but when trying to get float from quite horse-like input...)
What can we do with exception? We can catch it. First, a general exception:
...which handles both division by 0:
... and division by horse :)
The exception handling in Python is done using try except instruction. In the case above, no specific exception has been specified to be caught, so we get the same result in case of any exception (also known as Pokemon exception handling... Catch them all ;) ).
So what if we wanted to catch some specific exception?
Result:
What if we want to catch more specific exceptions?
We can specify more except blocks:
Division by 0 is then detected separately from division by horse:
and
That's all for now - the custom exceptions and throwing them "by hand" will be one of our next topics in the nearest future :)
No comments:
Post a Comment