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.

  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:

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

A Python program to understand the usage of try with finally blocks.