← All lessons

Specific exceptions

Sign in · Sign up

Lesson 8.2

An except without a type catches everything: a typo and a division by zero alike. Write a specific type in except:

except ValueError:
    print("Numbers are needed")
except ZeroDivisionError:
    print("You cannot divide by 0")
  • ValueError — the value is not suitable: int("hello");
  • ZeroDivisionError — division by zero: 10 / 0.

There can be several different errors: each except is in charge of its own type. When the program runs, the first matching except is chosen and the rest are skipped.

The check puts into a and b whatever the user typed. Work out int(a) / int(b) and print Result: <value>. With text and with zero the program must not crash: print two different hints.

Hint

Print the result in else — that's where it belongs.

Two different except blocks: ValueError for text and ZeroDivisionError for zero, each with its own message. result starts as None, so it can be seen at the end.