Using Try Except in Python

problem

You are learning programming and how to handle errors in your programs. Instead of letting your program crash, there is a way to handle the error and keep it running. In this post we will see an example of error handling.

SOLUTION

In Python we can use the built-in Try – Except statement. This mechanism allows us to wrap risky code and grab the error instead of letting the program crash. For example a risky piece of code would be opening a file for reading its content. It is risky because we do not know if the file exists; maybe it has been deleted or renamed.

For example:

try_except.py
				
					file = open("myfile.txt","r") # open file for reading

				
			
running

Executed it in the terminal and crashed as follows.

output
FileNotFoundException in Python

It resulted in a FileNotFoundError Exception.

error handling

In order to make the above program safe to errors we need to enclose the risky code in a try except statement as follows:

try_except.py
				
					try: #attempt the code and avoid crashing the program
   file = open("data.txt","r") # open file for reading
except FileNotFoundError:
   print("The file is not found. Please check") #error handling

				
			

At line 2 we put the “risky” code and if it crashes, the program flow goes to line 4 where the error is handled and we print a nice user friendly message.

output
try-except example output in Python

Now the program runs fine and exits with code 0 which means no error. In contrast earlier it returned with error code 1 meaning 1 error:

exit code python example
Finally section

In the try except statement we start with the try section where the risky code is put. Then we add the except section that if the error (Exception) occurs the code is executed. 

We can add a finally section optionally. In this block the code is always executed despite the error occurring. 

try_except.py
				
					try:
	#some code that might cause error
except Exception:
	# code to run if error occurs
finally:
	# Code to run despite of error occurrs or not
				
			
else section

We can add the else section optionally just after the except section. The code we put in here is executed only if there was no error in the try statement.

For example:

try_except.py
				
					try:
   print("safe code") # no error
except Exception:
   print("Error happened") #error handling
else:
   print("all good")
finally:
   print("finally the section executes")

				
			
output
try-except-else-finally in python example

conclusion

In synopsis, the try-except statement tries (try section) a code that is error prone and attempts to execute it. If an error occurs it goes to the except section and executes the code in there. If an else section is added, the code in there is executed if there was no error. Lastly, if a finally section is added the code in there is executed anyhow.

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

Google Analytics Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.

HotJar Cookies

We use Hotjar in order to better understand our users’ needs and to optimize this service and experience. Hotjar is a technology service that helps us better understand our users’ experience (e.g. how much time they spend on which pages, which links they choose to click, what users do and don’t like, etc.) and this enables us to build and maintain our service with user feedback. Hotjar uses cookies and other technologies to collect data on our users’ behavior and their devices. This includes a device's IP address (processed during your session and stored in a de-identified form), device screen size, device type (unique device identifiers), browser information, geographic location (country only), and the preferred language used to display our website. Hotjar stores this information on our behalf in a pseudonymized user profile. Hotjar is contractually forbidden to sell any of the data collected on our behalf.

For further details, please see the ‘about Hotjar’ section of Hotjar’s support site.