Types of Errors in Python?

In Python, the errors can be categorized into two main categories:

  • Syntax errors
  • Exceptions

Python Exceptions

The errors occur as a program is executed or running is called 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

Just for the information, the syntax errors are those that occur due to invalid syntax in the program. 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 provide it, a syntax error occurs as shown below:

>>> if ifnum==10

SyntaxError: invalid syntax

Handling exception by try except example

Before explaining how try-except statement works, have a look at this example. A user is asked to enter a year which is number and program tell 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:

Python try except

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 was 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 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 a unhandled exception.
  • You may use more than one except clause with the try statement. So, if there are chances that different type 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.

A Demo 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:

multiple except

You can see, the program caught multiple errors by using try with two exception clauses. Each except clauses executed as the error occurred and displayed their respective messages.

Using except clause without exception name

You may omit the error name in the 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 without crashing the program. You should use it carefully. Have a look in 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:

except errors

The same example is used as in above case, except the error handler is only one; that handled any error. For the TypeError and ZeroDivisionError, the except handler executed and displayed the message.

You may also use the except clause that way after handling all the errors specifically, in case if an unexpected error occurs.

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.

You may use the else clause after all except clauses. 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.')

try else

In the output figure, as numbers were entered and no errors raised so else part 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. Whether an error occurs or not the finally clause executes before leaving the try statement.

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.")

finally

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.

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!