Error handling

from __future__ import print_function # for python versions 2.6 or older
import sys

raise ..

# check value, if value is wrong give error message and stop program
x = -2

if x<0:
   raise ValueError('x must be a positive number')

try .. except ..

try:
  a block of commands  
except ErrorType:
(error exceptions) in case of error
  do additional commands related to error-type to handle the error without stopping the program



# wait as long as input is not a number
while True:
    try:
        x = int(input("Please enter a number: "))
        break
    except ValueError:
        print("Oops! That was no valid number. Try again...")



# in case of error, give additional error message and stop
try:
    x=10/0
except Exception as err:
    print('Error:',err)
    print('Error in setting x value')
    raise   
Error: division by zero
Error in setting x value
Traceback (most recent call last):
  File "testing_raise.py", line 15, in <module>
    x=10/0
ZeroDivisionError: division by zero


# same but using sys.exit() to reduce error messages
try:
    x=10/0
except Exception as err:
    print('Error:',err)
    print('Error in setting x value')
    sys.exit(1)
Error: division by zero
Error in setting x value



# same but continue even if error
try:
    x=10/0
except Exception as err:
    print('Error:',err)
    print('Error in setting x value')
print('continue..')
Error: division by zero
Error in setting x value
continue..

# repr(err) provides more details than print(err) → repr() str() print()
print(err)
division by zero
repr(err)
"ZeroDivisionError('division by zero',)"


# catch multiple error types
try:
    s=['a','b','c']
    x=int(s[6])
except (IndexError, ValueError) as err:
    repr(err)
"IndexError('list index out of range',)"

# catch multiple error types, one by one
try:
    s=['a','b','c']
    x=int(s[6])
except ValueError as err:
    repr(err)
except IndexError as err:
    repr(err)
"IndexError('list index out of range',)"


Error types

http://docs.python.org/3.3/library/exceptions.html




read more
https://docs.python.org/3.4/tutorial/errors.html