Exception in a program as a situation that occurs during runtime and programmer has no control on it.
A good program is one that has a code that handles an exception well i.e., in case an exception occurs, then the exception handling code written for it, will take over and do the necessary action.
Exception handling in python involves the use of try and except clauses wherein the code that may generate an exception is written in the try block and the code for handling the exception when the exception is raised, written in except block.
try: #write here the code that may generate an exception except: #write code here about what to do if the exception has occurred.
- The code between try and except clause is executed.
- If there is no exception, then only try clause will run.
- If any exception occurred, the try clause will be skipped and the except clause will run.
- A try statement can have more than one except clause
try: print("result of 10/5=", (10/5)) print("result of 10/0=", (10/0)) except: print("Denominator must not be zero.")
Output- result of 10/5= 2.0 Denominator must not be zero.
This is all about try- except clause in python.