Python
In this tutorial we will learn about exception handlings in Python.
An exception is an event that disrupts the normal execution of a given program.
In Python an exception is an object that represents an error.
When our Python program raises an exception it must be handled immediately otherwise it terminates the execution of the program.
We use the try
and except
block to handle exceptions in Python.
try
blockIf we have a piece of code that we think might raise an error we put that piece of code inside a try
block.
Syntax:
try:
#
# some code goes here...
#
except
blockWe use the except
block to handle the exception raised by the piece of code inside the try
block.
Syntax:
try:
#
# some code goes here...
#
except:
#
# some error handling code goes here...
#
A try
block can raise more than one type of exception and hence we can have multiple except
attached to a given try
block.
Syntax:
try:
#
# some code goes here...
#
except Exception1:
#
# some error handling code goes here...
#
except Exception2:
#
# some error handling code goes here...
#
else
blockThe else
block holds a piece of code that is executed if no error is raised.
Syntax:
try:
#
# some code goes here...
#
except:
#
# some error handling code goes here...
#
else:
#
# some code goes here...
#
finally
blockWe use the finally
block to put a piece of code that we want to execute regardless of the try-except block.
The finally
block is a good place to release resources like closing files or closing database connections.
Syntax:
try:
#
# some code goes here...
#
except:
#
# some error handling code goes here...
#
finally:
#
# some code goes here...
#
In the following Python program we are trying to create a new file using the open
function. If the file exists then it will raise an error which we will handle using the try-except block.
try:
# create new file
fobj = open("sample.txt", "x")
print("File created!")
except:
print("Failed to create file.")
The first time we run the above code we will get "File created!"
as the output.
If we run the code again for the second time it will raise an error as the file already exists and we will get "Failed to create file."
as the output.
In the following Python program we are using try-except-else
block.
try:
# create new file
fobj = open("sample.txt", "w")
print("File opened in write mode.")
except:
print("Failed to create file.")
else:
fobj.close()
print("File closed.")
If we execute the above code we will get the following output.
File opened in write mode.
File closed.
In the following Python program we are using try-except-finally
block.
try:
# create new file
fobj = open("sample.txt", "w")
print("File opened in write mode.")
except:
print("Failed to create file.")
finally:
fobj.close()
print("File closed.")
If we execute the above code we will get the following output.
File opened in write mode.
File closed.
In the following Python program we are taking user input and dividing them.
try:
# take user input
x = input("Enter 1st number x:")
y = input("Enter 2nd number y:")
# convert to number and divide
result = float(x) / float(y)
# output
print("x/y =", result)
except ZeroDivisionError:
# this handles specific error
# if y is 0 then this message is prompted
print("Can't divide by zero.")
except:
# this handles generalised error
print("An error occurred.")
And here are some of the outputs for the above code.
Enter 1st number x:10
Enter 2nd number y:20
x/y = 0.5
Enter 1st number x:10
Enter 2nd number y:unknown
An error occurred.
Enter 1st number x:10
Enter 2nd number y:0
Can't divide by zero.
ADVERTISEMENT