I'm a python beginner. Two quick questions on the code below:
- Why can't I ever execute the
print("printed valueError")? - Why does the else statement with
print("no error occurred")will print no matters what I put in?
The code:
def int_checker(a,b):
try:
if isinstance(a,int) and isinstance(b,int):
print('both integers')
else:
raise ValueError
print('printed ValueError')
except:
print('error occurred')
else:
print('no error occurred')
finally:
print('no error occurred')
print(int_checker(1,2))
print(int_checker(1,'a')
print('printedValueError')is right after araisestatement. When the exception is raised, execution goes to the except block, not to the next line. So that line is unreachable.finallystatement whereno error occuredis printed.print('no error occurred')is in afinallyblock. The point of afinallyblock is that it should always be executed regardless of what happens in yourtryblock.