\(\renewcommand\AA{\unicode{x212B}}\)
raise
keyword:# ...
# Execution stopped:
raise RuntimeError
try ... except
clauses,arr = [1,2,3,4,5]
for i in range(6):
try:
val = arr[i]
print(str(val))
except IndexError:
print('Error: List index out of range, leaving loop')
break
except
block. The output of the above code block is:1
2
3
4
5
Error: List index out of range, leaving loop
else
clause
that can be added which will only be executed if no error was raised,arr = [1,2,3,4,5]
value = 0
try:
value = arr[5]
except IndexError:
print('5 is not a valid array index')
else:
print('6th element is ' + str(value))
gives the output
5 is not a valid array index
try...except...else
structure only one of the except/else
clauses will ever be executed. In some circumstances however it is
necessary to perform some operation, maybe a clean up, regardless of
whether an exception was raised. This is done with a
try...except...finally
structure,value = 0
arr = [1,2,3,4]
element = 6
try:
value = arr[element]
except IndexError:
print(str(element) + ' is not a valid array index')
else:
print(str(element + 1 ) + 'th element is ' + str(value))
finally:
print('Entered finally clause, do cleanup ...')
gives the output
6 is not a valid array index
Entered finally clause, do cleanup ...
value = 0
arr = [1,2,3,4]
element = 6
try:
value = arr[element]
except: # Catch everything
print("Something went wrong but I don't know what")
gives the output
Something went wrong but I don't know what