Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Explain try, except and finally statements in Python.

When I am running the following code, I am getting an error.

'apple' + 6

OUTPUT

Traceback (most recent call last):
File "C:/Users/TutorialsPoint1/PycharmProjects/~.py", line 1, in
'apple' + 6
TypeError: cannot concatenate 'str' and 'int' objects

How to use try, except and finally statements in python to handle exceptions like above?


1 Answer
Manogna

In exception handling in Python, we use the try and except statements to catch and handle exceptions. The code within the try clause is executed statement by statement.

If an exception occurs, the rest of the try block is skipped and the except clause is executed.

try:
'apple' + 6
except Exception:
print "Cannot concatenate 'str' and 'int' objects"

OUTPUT

Cannot concatenate 'str' and 'int' objects

We avoid the traceback error message elegantly with simpe message like above by using try except statements for exception handling.

In addition to using an except block after the try block, we can also use the finally block. The finally clause is optional. It is intended to define clean-up actions that must be executed under all circumstances

A finally clause is always executed before leaving the try statement, whether an exception has occurred or not.

Actions  like closing a file, GUI or disconnecting from network are performed in the finally clause to guarantee execution.

Here is an example of file operations to illustrate finally statement.

try:
f = open("foo.txt",encoding = 'utf-8')
# perform file operations
finally:
f.close()

This type of statement makes sure that the file is closed whether an exception occurs or not.

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.