What is Exception Handling in Python
An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program’s instructions. Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not unconditionally fatal. Most exceptions are not handled by programs, however, and result in error messages as shown here:
>>> a=5 >>> b=0 >>> a/b Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: division by zero >>>
We can write programs that handle selected exceptions in our programs. We can handle exceptions using the try except statements.
If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem.
Syntax
try: You do your operations here; ...................... except ExceptionI: If there is ExceptionI, then execute this block. except ExceptionII: If there is ExceptionII, then execute this block. ...................... else: If there is no exception then execute this block.
A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions.
You can also provide a generic except clause, which handles any exception.
After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception.
The else-block is a good place for code that does not need the try: block’s protection.
try: a = 8 b = 0 print(a/b) except ZeroDivisionError: print("ZeroDivisionError is found. Check the denominator")
Output:
ZeroDivisionError is found. Check the denominator