D.S
D.S

Reputation: 105

Else statement in python

I'm a python beginner. Two quick questions on the code below:

  1. Why can't I ever execute the print("printed valueError")?
  2. 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')

Upvotes: 0

Views: 259

Answers (2)

Tatranskymedved
Tatranskymedved

Reputation: 4371

Why can't I ever execute the print("printed valueError")?

It is simply because the code execution will raise ValueError exception and that jumps directly to the except part. To resolve, You can switch lines:

else:
    print('printed ValueError')
    raise ValueError

Why does the else statement with print("no error occurred") will print no matters what I put in?

You are using syntax with try, catch, else, finally. The order of those is:

  1. Run code in try block.
  2. Did some error occured?
    • True: execute code in catch block
    • False: execute code in else block
  3. Run code in finally block. (This will happen always!)

From the above, the code form finally statement will be run everytime no matter if there was or wasn't error during execution. In most cases it is used e.g. when You open file in try block, read from it and suddenly an error occurs. In that case You want to close the file and clear the references. That code will go to the finally block.


Similar question on SO: Purpose of else and finally in exception handling

Upvotes: 1

Russ
Russ

Reputation: 26

Anything in the "finally" block will print every time.

Try this: remove the 'else' from "try" block and add the following to the 'except' block:

print('printed ValueError')
raise ValueError

The 'else' after 'except' will only run if no errors occur

Upvotes: 0

Related Questions