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.
Few examples of Exceptions
ZeroDivisionError
, 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
The only code that should go inside a
try
block is the code that might cause a specific exceptionIf the code in a
try
block works, Python skips theexcept
blockIf 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
blockIf more code follows after the
try-except
block, 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
In above example, we asked user to
input
two numbersthen 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 allowedhowever, if the user
input
both numbers, theelse
block will execute
3. Analyzing Text (using try-except)
In this example, we will combine the concepts learned until now:
rather than separately writing a
try-except-else
block, we wrapped it inside a functionin
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 correctif 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 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
Last updated
Was this helpful?