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