Python Exception Handling

In programming languages Exception handling is the process of responding to unwanted or unexpected events when a computer program runs. Exception handling helps a programmer in dealing with such events to avoid the program or system crash. If these events are not handled properly it will disrupt the normal operation of a program. Python has many built-in exceptions that are raised when your program encounters an error (something in the program goes wrong). When these exceptions occur, the Python interpreter stops the current process and passes it to the calling process until it is handled. If not handled, the program will crash.

Catching Exceptions in Python

In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause. We can thus choose what operations to perform once we have caught the exception.

Python Try Except Blocks

The try block lets you test a block of code for errors.
The except block lets you handle the error.
The else block lets you execute code when there is no error.
The finally block lets you execute code, regardless of the result of the try- and except blocks

Consider this example :

try:
    file_name=input("Enter file name to open : ")
    with open(file_name) as f:
        print(f.read())
except FileNotFoundError:
    print("Sorry this file does not exits")

In the above example, if the file name not found the above program will generate exception and this exception will be handled and program will not terminate abnormally.

# Program to handle multiple errors with one
# except statement
# Python 3

def fun(a):
	if a < 4:
		# throws ZeroDivisionError for a = 3
		b = a/(a-3)

	# throws NameError if a >= 4
	print("Value of b = ", b)
	
try:
	fun(3)
	fun(5)
# note that braces () are necessary here for
# multiple exceptions
except ZeroDivisionError:
	print("ZeroDivisionError Occurred and Handled")
except NameError:
	print("NameError Occurred and Handled")

Consider an other example that have all the blocks of the Exception Handling

try:
  print("Hello")
except:
  print("Something went wrong")
else:
  print("Else Block of Try")
finally:
  print("Finally Block")

# Output 
# Hello
# Else Block of Try
# Finally Block

Raise an exception
In Python we can choose to throw an exception using code if we want to. To throw (or raise) an exception, use the raise keyword. Consider the example below :

try:
    a= int(input("Enter a positive integer: "))
    if a <= 0:
        raise ValueError("That is not a positive number!")
    else:
        print("You entered a +ive Integer", a)
except ValueError as ve:
    print(ve)

You may also like...

Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *