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

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.

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 exception

  • If the code in a try block works, Python skips the except block

  • If the code in the try block causes an exception, Python goes to except block, where exception matches the one that was raised, and runs the code in the except 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.

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 numbers

  • then we convert them into integer using int()

  • if user input string, the int() function will cause the ValueError and the code in except block will execute, telling user that only numbers are allowed

  • however, if the user input both numbers, the else 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 function

  • in try block, we opened the file and store its content inside the variable book_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, the else 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

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?