Python except keyword is used in Python Exception handling. Except is used with try block and if any exception occurs in the program, then except block will be executed.
Syntax of except
try : statements except : except_statements
except_statements will execute inside except only if any exception occurs in the try block.
Example of except
Let’s understand except with one example
x=2 try : r=x/0 except: print("number is divided by zero exception...")
number is divided by zero exception... after exception
In this example, we have variable x having some value when we divide this number with zero. The program throws an exception, that exception is handled by except block of Python, and statements inside except block will be executed.it also did not break the code flow as we can see that print(“after exception“) statement after executing block runs successfully.
Let’s try not to put except block and try to run the same program.
x=2 r=x/0 print("number is divided by zero exception...") print("after exception")
ZeroDivisionError: division by zero
See when we did not use except in the program, then the program stops after getting zeroDivision error.