Error handling

Python by examples

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')

see more examples ...

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 the 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 using 'raise'

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


# stop controlled by 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 in case of error (no stop command)

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() vs. print()

# repr(err) provides more details than print(err) → repr() str() print()

print(err)

division by zero

repr(err)

"ZeroDivisionError('division by zero',)"


Multiple error types

# 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',)"


read more

Error types and exceptions

https://docs.python.org/3/tutorial/errors.html

https://docs.python.org/3/library/exceptions.html