Python Exceptions Handling

In python, exceptions are those errors which occurs when changes takes place in the normal flow of a program due to internal events. In simple term...

In this article, we will discuss about how to handle python exceptions by using of try...except...finally statements, how to catch specific exceptions and raising exceptions with the help of examples.

Python Exceptions Handling

Python Exceptions

In python, exceptions are those errors which occurs when changes takes place in the normal flow of a program due to internal events. In simple terms, we can say that exception are raised when something goes wrong in the program. The python exceptions are also known as Logistic Errors

Catching Python Exceptions with Try and Except Statement

In python, statement is used for exception handling or catching exceptions. Programmers write the critical statement that can raise an exception inside the block and inside the block, the code which will handle the exception is written. Once we found out the exception, we can choose the operation to perform.

# A Python program to handle simple runtime error

x = [1, 2, 3]

try:

    print("Second element = %d" %(x[1]))

    print("Fourth element = %d" %(x[3]))

except:

    print("An error occurred!!")

Output

Second element = 2
An error occurred!!

Catching Specific Python Exceptions 

Python programming language also provides us the option of using multiple clause for handling each specific exception as there can be more than one exception in a program. Here, we can specify which exception should be catched by a particular clause.

try:

   # do something

   pass

except ValueError:

   # handle ValueError exception

   pass

except (TypeError, ZeroDivisionError):

   # handle multiple exceptions

   # TypeError and ZeroDivisionError

   pass

except:

   # handle all other exceptions

   pass

Python Try statement with Else Clause

Python also provides us an optional clause which can be used after the try-except block. The clause is written after the try and all except clauses. The code only enters the block when there is no exception raised by the block. If you want to run a specific block of code when the block of code inside the statement doesn't raise any errors or exceptions, then you can use the clause.

# A python 3 program to depict else clause with try-except

# Function which returns a/b

def math(x , y):

    try:

        z = ((x+y) / (x-y))

    except ZeroDivisionError:

        print ("x/y result in 0")

    else:

        print(z)

# This is a driver program to test above function

math(2.0, 3.0)

math(3.0, 3.0)

Output

-5.0
x/y result in 0

Python try...finally statement

In python, there is another clause i.e., which is optionally used with the try statement. This clause is always executed no matter what, after the try and except blocks. clause is used after try...except statement so that the external resources would be released. And even if any exception occurs in the execution of a program, this clause makes sure that the file is closed.

try:    

    file = open("demo.txt","r")      

    try:    

        file.write("Learn Python is easy with Answersjet")    

    finally:    

        file.close()    

        print("file closed")    

except:    

    print("Error")

Output

file closed
Error

Raising An Exception in Python

As we are aware of the fact that exceptions occurs at the runtime of a program but python also allows us to raise an exception manually with the help of Keyword. By using the keyword, we can raise any specific exception forcefully. And for clarification, we can pass values to that exception optionally.

try:  

     num = int(input("Enter a positive integer number: "))  

     if(num <= 0):  

# we can pass the message in the raise statement  

         raise ValueError("That is a negative integer number!")  

except ValueError as e:  

     print(e)

Output

Enter a positive integer number: -1
That is a negative integer number!

Conclusion

Above we have learnt about how to handle python exceptions by using of try...except...finally statements, how to catch specific exceptions and raising exceptions with the help of examples. Python exceptions are those errors which occurs when changes takes place in the normal flow of a program due to internal events. The statement is used for exception handling or catching exceptions. Python also allows us to raise an exception manually with the help of Keyword.