Python Core



Admission Enquiry Form


Exception Handling in Python

Error in Python can be of two types i.e.Syntax errors and Exceptions (runtime error). Errors are the problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the program.

Exceptions: Exceptions are raised when the program is syntactically correct, but the code resulted in an error. This error does not stop the execution of the program, however, it changes the normal flow of the program.

Note: Exception is the base class for all the exceptions in Python.

Common Exceptions:

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.

ZeroDivisionError: Occurs when a number is divided by zero.

NameError: It occurs when a name is not found. It may be local or global.

IndentationError: If incorrect indentation is given.

IOError: It occurs when Input Output operation fails.

EOFError: It occurs when the end of the file is reached, and yet operations are being performed.




What is exception handling in python?

Python provides a way to handle the exception so that the code can be executed without

any interruption. If we do not handle the exception, the interpreter doesn't execute

all the code that exists after the exception.

Python has many built-in exceptions that enable our program to run without interruption and give the output. These exceptions are given below:

The try-except statement:

If the Python program contains suspicious code that may throw the exception,

we must place that code in the try block. The try block must be followed with the except statement,

which contains a block of code that will be executed if there is

some exception in the try block.

try-catch in python

Syntax with Example

Syntax
try:    
    #block of code        
except Exception1:    
    #block of code    
 except Exception2:    
    #block of code  
Example 1
try:  
    a = int(input("Enter a:"))    
    b = int(input("Enter b:"))    
    c = a/b  
except:  
    print("Can't divide with zero") 

 



Output

zero divide exception



Catching Specific Exception:

A try statement can have more than one except clause, to specify handlers for different exceptions. Please note that at most one handler will be executed. For example, we can add IndexError in the above code. The general syntax for adding specific exceptions are – 
try:
# statement(s)

except IndexError:
# statement(s)

except ValueError:
# statement(s)




Try with Else Clause

In python, you can also use the else clause on the try-except block which must be present after all the except clauses. The code enters the else block only if the try clause does not raise an exception.
The syntax to use the else statement with the try-except statement is given below.
try:    
    #block of code  
except Exception1:    
    #block of code     
else:    
    #this code executes if no except block is executed    




try except and else block in python

Example:

try:    
    a = int(input("Enter a:"))    
    b = int(input("Enter b:"))    
    c = a/b  
    print("a/b = %d"%c)    
# Using Exception with except statement. If we print(Exception) it will return 
exception class  
except Exception:    
    print("can't divide by zero")    
    print(Exception)  
else:    
    print("Hi I am else block")     



Output

try else block in python



Finally Keyword in Python:

Python provides a keyword finally, which is always executed after the

try and except blocks. The final block always executes after normal termination
of try block or after try block terminates due to some exception.

It is executed no matter what exception occurs and used to release the external resource. The finally block provides a guarantee of the execution.

Syntax
try:    
    # block of code     
    # this may throw an exception    
finally:    
    # block of code    
    # this will always be executed     




try with finally block

Example:

try:    
    fileptr = open("file2.txt","r")      
    try:    
        fileptr.write("Hi I am good")    
    finally:    
        fileptr.close()    
        print("file closed")    
except:    
    print("Error")    



Output

try with finally blick output