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-exceptblock, 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.
Few examples of Exceptions
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 implicitlyZeroDivisionError, NameError and TypeError in above examples are example of exception objects.
1. Handling Exceptions
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 block
try:
answer = 5/0
except ZeroDivisionError:
print("You can't divide a number with zero")You can't divide a number with zeroThe only code that should go inside a
tryblock is the code that might cause a specific exceptionIf the code in a
tryblock works, Python skips theexceptblockIf the code in the
tryblock causes an exception, Python goes toexceptblock, where exception matches the one that was raised, and runs the code in theexceptblockIf more code follows after the
try-exceptblock, it will be executed as normal because we told Python how to handle the error.
2. The else Block
Any code that should be executed, if the try block runs successfully, goes into the else block. Example will make the concept clearer
try:
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 allowedIn above example, we asked user to
inputtwo numbersthen we convert them into integer using
int()if user input string, the
int()function will cause theValueErrorand the code inexceptblock will execute, telling user that only numbers are allowedhowever, if the user
inputboth numbers, theelseblock will execute
3. Analyzing Text (using try-except)
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 timesrather than separately writing a
try-except-elseblock, we wrapped it inside a functionin
tryblock, we opened the file and store its content inside the variablebook_contentif the file doesn’t exist at given path, the
exceptblock will be executed, telling that the file path is not correctif the
tryblock executes successfully, theelseblock will be executed, telling the number of words in the book and count of user provided keyword in the booklastly, 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
4. Failing Silently
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 block
try:
answer = 5/0
except ZeroDivisionError:
passLast updated
Was this helpful?