Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

What are errors and exceptions in Python?

Aduragbemi

Overview

Errors and bugs, faults, or problems can occur in a program and cause it to stop executing or to behave abnormally.

In this shot, we will discuss the two types of errors in Python:

  • Syntax errors
  • Exceptions

Syntax errors

Syntax errors, also called parsing errors, are errors that occur as a result of incorrect syntax in any part of the code/program. The syntax is a rule that states how words and phrases must be used in Python.

A syntax error occurs when any aspect of the code does not conform with the programming language syntax; in this case, the Python language.

Examples of syntax errors

print(5 x 5)

The arrow indicates where the error was detected. In the code above, x is not the Python syntax (operator) used for multiplication; instead, we use the asterisk (*). In some cases, the arrow points to where the error is (just like the example above). In others, the arrow comes after the error.

name = {'firstname':['aduragbemi', 'messi']
  'lastname': ['oyinlol', 'lionel']
}

In the example above, the error is detected in the second line because the comma after the values for the firstname key is missing, and the comma is necessary to tell Python you are done with the key-value pair for firstname.

Exceptions

Exceptions are another group of errors that occur if an error occurs during runtimethe period of time when a program runs after it passes the syntax test..

Exceptions are errors that occur when your program follows the rules of writing in a space of time and still returns errors.

Here are some exceptions that occur in a program:

  • ValueError
  • AttributeError
  • NameError
  • TypeError
  • IndexError
  • KeyError
  • ZeroDivisionError

We will go over a few of the listed exceptions.

Examples of exceptions

4 + 'name'

Let’s take a look at the syntax. The number 4 is correct, as an integer can be written directly. The addition sign + is correct, and the string is quoted properly.

The code above passes both the runtime and syntax. You can add an integer and string, just like in mathematics.

name = 'aduragbemi'
print(nmae)

A variable name is defined and given a value, aduragbemi, and is quoted properly. The error in this example is calling name as nmae.

fruits = ['apple', 'orange', 'banana', 'peach', 'grapes']
print(fruits[5])

In the example above, a list of fruits is passed to a variable fruits, and the elements in the list are quoted. The length of the list is 5, but Python is zero-indexthe counting starts from zero, so the last element in the list can be called when 1 is subtracted from the length of the list.

RELATED TAGS

python
communitycreator
RELATED COURSES

View all Courses

Keep Exploring