Searching for Try except in Python? Python try except blocks helps us handle exceptions that occur while our code executes.
Exceptions are errors that occur due to unusual events which disrupts the normal flow/execution of our program while running. Some examples include
- The program tries to divide by zero
- Our code could not find a file
- Or program used too much memory
In any case, exceptions stop our programs from executing and are unpleasant to our users. In this tutorial, we will discuss how to use the try-except
construct in Python to handle exceptions. Specifically, we will show how to
- Manually raise exceptions
- Handle exceptions
- Handle multiple exceptions
- Continue execution with try except else
- Define clean up actions
Manually Raise Exceptions
When python raises an exception, python displays a message which describes the exception, and which line the exception occurred in our code. We can illustrate with an example
# invalid division
quotient = 12 / 0
Output:
ZeroDivisionError Traceback (most recent call last)
in
----> 1 quotient = 12 / 0
ZeroDivisionError: division by zero
This first example is descriptive. It shows an attempt by our program to divide by zero. Python raises an exception telling us about it.
Python also allows us to manually raise exceptions by using the raise
keyword.
# define a function to greet someone
def greet(name):
if type(name) != str:
raise Exception("name must be a string")
else:
print(f"Hello {name}, nice to meet you")
# the following line will not raise an exception
greet("Harry")
# the next line will raise an exception
greet(34)
Output:
Exception Traceback (most recent call last)
in
10
11 # the nex\t line will raise an exception
---> 12 greet(34)
in greet(name)
1 def greet(name):
2 if type(name) != str:
----> 3 raise Exception("name must be a string")
4
5 else:
Exception: name must be a string
Handling Exceptions in Python Try Except Blocks
If we suspect that a section of code will raise an exception, we can make use of the try-except
block to handle the exception. The next code segment illustrates how to use the try-except
block in python.
def greet(name):
if type(name) != str:
raise Exception("name must be a string")
else:
print(f"Hello {name}, nice to meet you")
try:
# greet with an invalid value
greet(34)
except Exception as e:
# print a nice message to the user
print(e)
Output:
name must be a string
The try
section tests the code segment for errors. When an error occurs within the try
block, execution moves to the except
block. However, if no error is encountered within the try
block, execution moves to any code after the try-except
blocks.
In the previous code, we just decided to print out the message contained within the exception object. We could decide to print a different message within the except
block, as found in the next code.
def greet(name):
if type(name) != str:
raise Exception("name must be a string")
else:
print(f"Hello {name}, nice to meet you")
try:
# greet with an invalid value
greet(34)
except Exception as e:
# print a nice message to the user
print("An error was encountered. User greeting cannot be displayed")
Output:
An error was encountered. User greeting cannot be displayed
Handling multiple Python errors
The following code raised a division by zero exception
def greet(name):
if type(name) != str:
raise Exception("name must be a string")
else:
print(f"Hello {name}, nice to meet you")
try:
# try to divide by zero
quotient = 12 / 0
# greet with an invalid value
greet(34)
except ZeroDivisionError as e:
print(e)
When we execute the program, we get the following message
Output:
division by zero
We handled the division by zero error without crashing the program.
What would happen if we corrected the division by zero line?
The line after the division would crash the program!
def greet(name):
if type(name) != str:
raise Exception("name must be a string")
else:
print(f"Hello {name}, nice to meet you")
try:
# try to divide
quotient = 12 / 1
# greet with an invalid value
greet(34)
except ZeroDivisionError as e:
print(e)
Output:
Exception Traceback (most recent call last)
in
12
13 # greet with an invalid value
---> 14 greet(34)
15
16 except ZeroDivisionError as e:
in greet(name)
1 def greet(name):
2 if type(name) != str:
----> 3 raise Exception("name must be a string")
4
5 else:
Exception: name must be a string
What caused the crash?
The except
block was only written to handle the zero division error, but not the one raised by the greet()
function. To remedy this, we will add another except
block to handle the more general Exception
error.
def greet(name):
if type(name) != str:
raise Exception("name must be a string")
else:
print(f"Hello {name}, nice to meet you")
try:
# try to divide
quotient = 12 / 1
# greet with an invalid value
greet(34)
except ZeroDivisionError as e:
print(e)
except Exception as e:
print(e)
Output:
name must be a string
The above code now handles the error raised by the functiongreet()
. We can make use of multiple except
blocks to handle different kinds of errors that could be raised from a try
block.
However, since ZeroDivisionError
is derived from Exception
, the except
blocks were arranged in such a way that ZeroDivisionError
was checked first before Exception
. If the base class (Exception
) except
block was placed before the derived class except
block, the except
block for ZeroDivisionError
would never be reached. This is because ZeroDivisionError
is also an Exception
.
Continue execution with Python Try Except Else
You might need to do some actions specific to the statements tested in the try block when no error occurred. We use the else
block for this purpose.
def greet(name):
if type(name) != str:
raise Exception("name must be a string")
else:
print(f"Hello {name}, nice to meet you")
try:
# greet with a valid string value
greet("John")
except:
# print a nice message to the user
print("An error was encountered. User greeting cannot be displayed")
else:
print("See you next time!")
Output:
Hello John, nice to meet you
See you next time!
Define cleanup actions with python try except finally
The finally
block is executed whether or not python encounters an error while executing our code.
To illustrate the usefulness of the finally
block, the code below tries to write to an output string with a maximum capacity of 15 characters. We defined two functions to help
append_stars()
takes a numbern
, and appendsn
asterisks to the output if there is available space. If not, it raises an exceptiontry_append()
takes a list of integers, each integer representing the number of asterisks to append to the output string
# append n stars to output
def append_stars(n):
global output_string
global output_capacity
if len(output_string) + n > output_capacity:
# number of characters in output_string plus n is
# more than the capacity of output_string
raise Exception("cannot add more characters to output string because doing so will surpass capacity of output string")
else:
# append n strings to output_strings
output_string += '*' * n
# try the appending operation here
def try_append(lst):
global output_string
print(f"Trying to append {lst} to output string...")
for n in lst:
print(f"\tcurrent number: {n}")
repeated_stars(n)
# display the final output
print(f"\tAppend succeeded. Output is : {output_string}, ({len(output_string)} characters)\n\n")
## main program
output_string = ""
output_capacity = 15
# first try will succeed
try_append([1, 3, 5, 2, 1])
# second try will fail
try_append([2, 5, 8, 4, 3, 1, 4, 3, 6])
# third try will succeed
try_append([2, 1, 3, 1, 1, 1, 4, 1])
Output:
Trying to append [1, 3, 5, 2, 1] to output string...
current number: 1
current number: 3
current number: 5
current number: 2
current number: 1
Append succeeded. Output is : ************, (12 characters)
Trying to append [2, 5, 8, 4, 3, 1, 4, 3, 6] to output string...
current number: 2
current number: 5
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
in
38
39 # second try will fail
---> 40 try_append([2, 5, 8, 4, 3, 1, 4, 3, 6])
41
42 # third try will succeed
in try_append(lst)
22 for n in lst:
23 print(f"\tcurrent number: {n}")
---> 24 repeated_stars(n)
25
26 # display the final output
in repeated_stars(n)
7 # number of characters in output_string plus n is
8 # more than the capacity of output_string
----> 9 raise Exception("cannot add more characters to output string because doing so will surpass capacity of output string")
10
11 else:
Exception: cannot add more characters to output string because doing so will surpass capacity of output string
The main segment of the program tried to call try_append()
three times, but the call failed at the second attempt.
Why did this happen?
We could view the variable output_string
as a memory resource that was used, but not freed after the first call to try_append()
. The second call encountered an error because output_string
quickly filled up before try_append()
finished.
To solve this problem, the next program makes use of a try-except-else-finally
block to both handle the error from append_stars()
, and free up output_string
, before the next call of try_append()
.
# append n stars to output
def append_stars(n):
global output_string
global output_capacity
if len(output_string) + n > output_capacity:
# number of characters in output_string plus n is
# more than capacity of output_string
raise Exception("cannot add more characters to output string because doing so will surpass capacity of output string")
else:
# append n strings to output_strings
output_string += '*' * n
# try the appending operation here
def try_append(lst):
global output_string
print(f"Trying to append {lst} to output string...")
try:
for n in lst:
print(f"\tcurrent number: {n}")
repeated_stars(n)
except:
print(f"\tAppend failed because output capacity is filled. (max capacity = {output_capacity} characters)\n\n")
else:
# display the final output
print(f"\tAppend succeeded. Output is : {output_string}, ({len(output_string)} characters)\n\n")
finally:
# clear the output so that the next try attempt can use it
output_string = ""
## main program
output_string = ""
output_capacity = 15
# first try will succeed
try_append([1, 3, 5, 2, 1])
# second try will fail
try_append([2, 5, 8, 4, 3, 1, 4, 3, 6])
# third try will succeed
try_append([2, 1, 3, 1, 1, 1, 4, 1])
Output:
Trying to append [1, 3, 5, 2, 1] to output string...
current number: 1
current number: 3
current number: 5
current number: 2
current number: 1
Append succeeded. Output is : ************, (12 characters)
Trying to append [2, 5, 8, 4, 3, 1, 4, 3, 6] to output string...
current number: 2
current number: 5
current number: 8
current number: 4
Append failed because output capacity is filled. (max capacity = 15 characters)
Trying to append [2, 1, 3, 1, 1, 1, 4, 1] to output string...
current number: 2
current number: 1
current number: 3
current number: 1
current number: 1
current number: 1
current number: 4
current number: 1
Append succeeded. Output is : **************, (14 characters)
The finally
block allows the program to release output_string
so that we can make another call to try_append()
.
Conclusion
That’s it for this tutorial on try-except
in Python. We hope you found the information useful. Thanks for reading!
If you are in a need of any python help or looking for someone who can help with python then feel free to drop us a message.