How do yo handle exception in python?

Last updated 3 weeks, 4 days ago | 25 views 75     5

Tags:- Python

Python | Exception Handling

Python has many built-in exceptions that are raised when your program encounters an error.

Try and Except Statement – Catching Exceptions:

Try and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause.

a = [1, 2, 3]
try:
    print ("Second element = %d" %(a[1]))
    # Throws error since there are only 3 elements in array
    print ("Fourth element = %d" %(a[3]))
except:
    print ("An error occurred")
 

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.
 

# print the reciprocal of even numbers

try:
    num = int(input("Enter a number: "))
    assert num % 2 == 0
except:
    print("Not an even number!")
else:
    reciprocal = 1/num
    print(reciprocal)

Python try...finally:

The try statement in Python can have an optional finally clause. This clause is executed no matter what and is generally used to release external resources. For example, we may be connected to a remote data center through the network or working with a file or a Graphical User Interface (GUI).

In all these circumstances, we must clean up the resource before the program comes to a halt whether it successfully ran or not. These actions are performed in the finally clause to guarantee the execution.
 

try:
   f = open("test.txt",encoding = 'utf-8')
finally:
   f.close()

Raising Exception:

We can also manually raise exceptions using the raise keyword. We can optionally pass values to the exception to clarify why that exception was raised.
 

try:
    raise NameError("Hi there")  # Raise Error
except NameError:
    print ("An exception")
    raise  # To determine whether the exception was raised or not