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
The 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
In 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:
rather 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
Last updated
Was this helpful?