Handling Exceptions In Python
Python uses special objects called
exceptions
to handle errors that arise during a program’s execution (as opposed to Syntax errors). Therefore whenever an error occurs, Python creates an exception object- If we write the code that handles the exception using
try-except
block, the program will continue running. - If we don’t handle the exception, the program will halt and show a
traceback
, which includes a report of the error that was raised.
10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
4 + spam*3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'spam' is not defined
'2' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
ZeroDivisionError
, NameError
and TypeError
in above examples are example of exception objects.While writing the code, if we know that a specific type of error may occur, we can write a
try- except
block to handle that particular exception . Here is a quick example to deal with ZeroDivisionError
using try-except
blocktry:
answer = 5/0
except ZeroDivisionError:
print("You can't divide a number with zero")
You can't divide a number with zero
- The only code that should go inside a
try
block is the code that might cause a specific exception - If the code in a
try
block works, Python skips theexcept
block - If the code in the
try
block causes an exception, Python goes toexcept
block, where exception matches the one that was raised, and runs the code in theexcept
block - If more code follows after the
try-except
block, it will be executed as normal because we told Python how to handle the error.
Any code that should be executed, if the
try
block runs successfully, goes into the else
block. Example will make the concept clearertry:
first_number = input("Enter first number: ")
int(first_number)
second_number = input("Enter the second number: ")
int(second_number)
sum = int(first_number) + int(second_number)
except ValueError:
print("Only numbers are allowed")
else:
print(f"The sum of {first_number} and {second_number} is {sum}")
EXAMPLE 1:
Enter first number: 10
Enter the second number: 20
The sum of 10 and 20 is 30
EXAMPLE 2:
Enter first number: 10
Enter the second number: twenty
Only numbers are allowed
- In above example, we asked user to
input
two numbers - then we convert them into integer using
int()
- if user input string, the
int()
function will cause theValueError
and the code inexcept
block will execute, telling user that only numbers are allowed - however, if the user
input
both numbers, theelse
block will execute
In this example, we will combine the concepts learned until now:
# writing a function to count words
def count_word_instances(file_path, word_to_count):
# using try except block to handle FileNoTFoundError
try:
with open(file_path) as book_object:
book_content = book_object.read()
except FileNotFoundError:
print("Given file path is not correct, please correct it.")
else:
word_count = book_content.lower().count(word_to_count)
words = book_content.split()
print(f"The book has approx {len(words)} words")
print(f"The word {word_to_count} appered {word_count} times")
# providing the path to file
file_path_here = "alice_book.txt"
# asking user to input the desired word
word_to_watch_here = input("What word would you like to search: ")
# calling function
count_word_instances(file_path_here, word_to_watch_here)
What word would you like to search: love
The book has approx 124592 words
The word love appeared 122 times
- rather than separately writing a
try-except-else
block, we wrapped it inside a function - in
try
block, we opened the file and store its content inside the variablebook_content
- if the file doesn’t exist at given path, the
except
block will be executed, telling that the file path is not correct - if the
try
block executes successfully, theelse
block will be executed, telling the number of words in the book and count of user provided keyword in the book - lastly, we call to this function, by giving the filename and words to count
- as the file name was correct, Python told us the number of words and count of word provided by the user
In the previous example, using a custom message in
except
block, we informed our users that file is unavailable. But, if we want, we don’t need to report exception — this behavior is called ** failing silently** and program continue on as if nothing happened. To make a program fail silently, we write a try
block as usual, but explicitly tell Python to do nothing in the except
block. To do nothing, we will use pass
statement in except
blocktry:
answer = 5/0
except ZeroDivisionError:
pass
Last modified 4mo ago