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.

Except Block

Except can be written in various formats.

  1. To catch the exception which is raised in the try block, we can write except block with the Exceptionclass name as:
  2. except Exceptionclass:

  3. We can catch the exception as an object that contains some description about the exception.
  4. except Exceptionclass as obj:

  5. 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:
  6. except (Exceptionclass1, Exceptionclass2,...):

  7. 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:

In previous program we are catching two exceptions using two except blocks. The same can be written using a single except block as:

CopiedCopy Code
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.')

Example without except block

CopiedCopy Code

#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)