In Python, the errors can be categorized into the following:
- Syntax errors
- Exceptions
Python Exceptions
The errors occur as a program is executed or running is called an exception.
These errors must be handled or a program will crash and may leave a confusion or bad impression on the user’s part.
For example, you are taking the user input that must be a number. Accidentally, a user enters a string and you have used this in a function that requires an integer. Then, an exception may occur and the program will crash.
As a Python programmer, you may handle these kinds of errors in the program by try..except..else..finally statements/clause and this is the topic of this tutorial.
See the details of using these statements with examples in the next section.
Syntax Errors
As you run a program, a message display and details of the error is displayed.
For example, an if statement requires a colon at the end. If you do not write, a syntax error occurs as shown below:
>>> if ifnum==10
SyntaxError: invalid syntax
Handling exceptions by try-except example
Before explaining how the try-except statement works, have a look at this example.
A user is asked to enter a year which is number and the program tells whether it is a leap year or not.
If the user enters a character like a-z, then a ValueError occurs.
See, this is how it is handled by using the try-except.
#A Demo of try-except try: Year = int(input("Please Enter a Year? ")) leap_or = Year%4 == 0 if leap_or: print ("This is a leap year") else: print ("This is not a leap year") except ValueError: print ("Only digits are allowed!")
Output:
In the output, you can see three possibilities. First, a year entered was not a leap year.
Second, the year entered was a leap year. The third time, the value entered was “year”, so it generated ValueError, and the corresponding message displayed “Only digits are allowed”.
So, how try-except statement works?
- First of all, the statements inside the try clause are executed.
- If no error occurs, as in the case of entries 2001 and 2008 in the example, the except clause is skipped.
- If an error occurs, as in case of “year” entry in the example, the execution moves to the except block. If a match to the error is found (like in our example TypeError), the except block executes.
- If the exception is not named in the except part then the execution is passed to the outer try statements. In that case, if error handler is not found, the execution stops with the error message and this is called an unhandled exception.
- You may use more than one except clause with the try statement. So, if there are chances that different types of exceptions may occur in your program, you may use multiple except clauses. Only one error handler will be executed.
- You may provide more than one error names by using a tuple for an except clause. That means, enclose multiple error names in parenthesis e.g. except (TypeError, NameError):
The following section shows examples of multiple try-except blocks and later you may also see using the else and finally clauses examples with detail.
An example of catching multiple exceptions
In this example, multiple except clauses are used to catch and handle errors.
For that, a list of mixed items is created. A for loop is used to iterate through the list elements.
In each iteration, the current item of the list is divided by a numeric type variable.
Now, a TypeError will be raised if the current item in the list is non-numeric.
Similarly, ZeroDivisionError will be raised if the current item is 0. For both errors to occur, the list is created with a string and 0 elements.
#Multiple except statements examples num_list = [5, 'c', 20, 0, 40] b = 15 for x in num_list: try: c = b / x print(c) except ZeroDivisionError: print("An element with 0 value") except TypeError: print("Only numbers can be used")
Output:
Only numbers can be used
0.75
An element with 0 value
0.375
You can see, the program caught multiple errors by using try with two exception clauses. Each except clause executed as the error occurred and displayed their respective messages.
Using except clause without an exception name
You may omit the error name in Python except clause.
In that case, the except clause will serve as a wildcard. So, if any error occurs, the except clause without any error name will execute and the program will now crash.
You should use it carefully. Have a look at the following example:
#Example of except without error name num_list = [13, 'f', 60, 0, 50] b = 15 for x in num_list: try: c = b / x print(c) except: print("An error occurred")
Result:
An error occurred
0.25
An error occurred
0.3
The same example is used as in above case, except the error handler is only one; that handled any error.
You may also use the except clause that way after handling all the errors specifically, in case an unexpected error.
Using else clause with try statement
The purpose of the (optional) else clause in the try-except block is to enable executing the code if try-except does not raise an exception.
See the following example for learning how to use the try-except with the else clause:
#An example of else clause with try-except try: a_number=int(input('Your Number? ')) except: print ('Enter a Number.') else: eve_or_odd = a_number%2 == 0 if eve_or_odd: print('You entered even number.') else: print('An Odd number.')
In the output figure, as numbers were entered and no errors raised so else part was executed.
The third time, a string was entered that raised an error, so the error handler executed while no statement in the else executed.
The Finally clause
There is another optional clause as working with try-except for catching errors in Python. This is called finally clause and it will execute in all circumstances.
See a simple example of using the finally clause:
try: a_number=int(input('Your Number? ')) except: print ('Enter a Number.') else: eve_or_odd = a_number%2 == 0 if eve_or_odd: print('You entered even number.') else: print('An Odd number.') finally: print("Thank you for using the program.")
Usage of the finally clause:
The general use of finally clause is releasing the external resources e.g. closing a database connection, closing a file, etc. whether program ran successfully or not.