Python Except Block
The 'except' block is useful to catch an exception that is raised in the try block. When there is an exception in the try block, then only the except block is executed. It is written in various formats.
- To catch the exception which is raised in the try block, we can write except block with the Exceptionclass name as:
- We can catch the exception as an object that contains some description about the exception.
- To catch multiple exceptions, we can write multiple catch blocks. The other way is to use a single except block and write all the exceptions as a tuple inside parentheses as:
- To catch any type of exception where we are not bothered about which type of exception it is, we can write except block without mentioning any Exceptionclass name as:
except Exceptionclass as obj:
except (Exceptionclass1, Exceptionclass2,...):
In previous program we are catching two exceptions using two except blocks. The same can be written using a single except block as:
except (TypeError, ZeroDivisionError): print('Either TypeError or ZeroDivisionError occurred.')
The other way is not writing any exception name in except block. This will catch any type of exception, but the programmer cannot determine specifically which exception has occurred. For example,
except: print('Some exception occurred.')
Python Example without except block
#try without except block try: x = int(input('Enter a number:')) y = 1/ x finally: print("We are not catching the exception.") print("The inverse is:", y)