Overview:
- The else clause for a try block is executed if there is no exception generated and no return statement, continue statement or break statement has been executed.
- The else clause is optional for a try block.
- The exception handling mechanism in Python is provided through the keywords : try, except, from, else, finally and raise.
Example:
def div(param1, param2): quotient = param1/param2; return quotient;
try: p1 = 1; p2 = 100; n1 = div(p1,p2); print("p1/p2 is %d"%n1);
p1 = 2; p2 = 100; n1 = div(p1,p2); print("p1/p2 is %d"%n1); except Exception as Ex: print("Exception: %s"%Ex); else: print("All div operations successful"); |
Output:
p1/p2 is 0 p1/p2 is 0 All div operations successful |