Hey! Hope you are doing great.
Today let us see what are exceptions in python

An exception can be defined as an unusual condition in a program resulting in the interruption in the flow of the program. Whenever an exception occurs, the program stops the execution, and thus the further code is not executed. Therefore, an exception is the run-time errors that are unable to handle to Python script. An exception is a Python object that represents an error.

To handle the exception we use try-except block. 

Python provides the number of built-in exceptions, but here we are describing the common standard exceptions. A list of common exceptions that can be thrown from a standard Python program is given below.

  1. ZeroDivisionError: Occurs when a number is divided by zero.
  2. NameError: It occurs when a name is not found. It may be local or global.
  3. IndentationError: If incorrect indentation is given.
  4. IOError: It occurs when Input Output operation fails.
  5. EOFError: It occurs when the end of the file is reached, and yet operations are being performed.
Without exceptions:






In Python, we use the Try and Except statements to handle these issues.
The try block is used to check for mistakes in code, the code inside the try block will run if the program contains no problems. The code in the except block will run if the program meets an error in the try block before it.

Syntax:
    
    
  1. try:    
  2.     #block of code     
  3. except Exception1:    
  4.     #block of code    
  5. except Exception2:    
  6.     #block of code    
  7. #other code   

A simple example for exceptions is ZeroDivisionError:

  1. n1=8
  2. n2=0
  3. try:
  4.    res=n1/n2
  5. except ZeroDivisionError:
  6.       print('Error')
    
Output:

Error


A keyword finally can also be used in Python. After the try and except blocks, finally is always executed. The final block is always executed after the try block has terminated normally or owing to some exceptions.

Syntax:

  1. try:    
  2.     # block of code     
  3.     # this may throw an exception    
  4. exception:
  5.        # block of code
  6. finally:    
  7.     # block of code this will always be executed   

Comments