Python-Ref > Basic usage > Exceptions > What is an exception
 
 

^^->
Klíčová slova
Moduly
Knihovní funkce

What is an exception

In case something goes wrong in your program and the Python interpreter no longer knows what to do, it "throws an exception". That is, it lets you know that some exceptional, unaccounted for, thing has happened.
It is your problem to deal with exceptions. If you don't, your program will crash.
The following program throws an exception and it is not caught..
Expand/Shrink
Zdroj: (exception1.1.py)
  1   print 1/0  # division by zero
stderr:
Traceback (most recent call last):
  File "exception1.1.py", line 1, in ?
    print 1/0  # division by zero
ZeroDivisionError: integer division or modulo by zero
Doba běhu: 21.1 ms
.. therefore it crashes.
The next program is wiser and takes care of the problem.
Expand/Shrink
Zdroj: (exception1.2.py)
  1   try:   # if the following code throws an exception, it is caught in 'except'
  2       print 1/0  # division by zero
  3   except:
  4       print "you cannot divide by zero"
stdout:
you cannot divide by zero
Doba běhu: 20.9 ms
Exceptions have different "values" in order to help you distinguish between different sources of the problem. It is usually good to write the except clause only for the case you are really prepared to deal with.
Expand/Shrink
Zdroj: (exception1.3.py)
  1   try:   # if the following code throws an exception, it is caught in 'except'
  2       print 1/0  # division by zero
  3   except ZeroDivisionError:
  4       print "you cannot divide by zero"
stdout:
you cannot divide by zero
Doba běhu: 21.0 ms
The following program demonstrates the case where two things could go wrong.
Expand/Shrink
Zdroj: (exception1.4.py)
  1   try:   # if the following code throws an exception, it is caught in 'except'
  2       print x/0  # no such variable x, division by zero
  3   except ZeroDivisionError:
  4       print "you cannot divide by zero"
  5   except:
  6       print "unknown error"
stdout:
unknown error
Doba běhu: 21.0 ms