Exception handing in python
Exception or Error is a abnormal condition and if that occurs then it exited from the main program with out executing the next statements and Exception handling is a way to handle that exception properly so that it can notify us that exception occurred and execute the next statements and not exiting from the middle of the program.
- How to handle an exception?We can use try, except, else, finally block to handle the exception
- What is try block? try block is where the exception occurred or generated.
- What is except block? where the exception is cached and handled
- What is else block? If exception does not occurred then this block is executed.
- What is finally block? finally block will always be executed if the exception is occurred or not.
- How to throw an Exception in python? In python we can use ‘raise’ keyword to throw an exception.
Get Surajit Mishra’s stories in your inbox
Join Medium for free to get updates from this writer.
def div(val1,val2):
if val2 == 0:
raise ZeroDivisionError()
return (val1/val2)
def main():
try:
d=div(10000000000,0)
print(d)
except:
print('ZeroDivisionError')
else:
print('next statements----------if exception does not occur------')
finally:
print('I m a finally statement-----------')
print('I dont care if exception occured or not')
print('Next statements after exception.....')
print('Next statements after exception.....')
if __name__ == '__main__':
main()In summery exception handling is a very important and handy tool for the developer to avoid abnormal conditions such as Exception and errors.








