Errors and Exceptions in Python

This post is lesson 30 of 54 in the subject Python Programming Language

With errors and exceptions in Python, we will encounter errors when programming as well as when running programs. In Python, we can divide errors into 2 types: syntax error and exception.

1. Syntax Error in Python

One of the errors and exceptions in Python is Syntax error also called parsing error. This error occurs because we do not follow the syntax of Python when programming. Syntax error usually occurs when we start learning Python and do not understand Python syntax well.

Example of Syntax Error in Python

# SyntaxError: expected ':'
if a < 3
  print("a is smaller than 3")

In the example above, the if statement is missing ‘:‘, causing a syntax error.

# SyntaxError: invalid syntax
while True:
  print(Hello world)

In the example above, the argument of the print function is not enclosed in quotes, causing a syntax error.

2. Exception Error in Python

Another error and exception in Python are Runtime errors are called exceptions or logical errors. Many cases can cause exceptions. For example, when we open a non-existent file, we encounter an exception called FileNotFoundError. Or dividing a number by 0 will encounter an exception called ZeroDivisionError. Or if we import a non-existent module, we will encounter an exception called ImportError.

When an exception occurs, Python creates an exception object. Python will stop the program and print error messages if these exceptions are not handled.

# ZeroDivisionError: division by zero
x = 1/0
# NameError: name 'spam' is not defined
y = 4 + spam*3
# TypeError: can only concatenate str (not "int") to str
z = '2' + 2
# FileNotFoundError: [Errno 2] No such file or directory: 'imaginary.txt'
open("imaginary.txt")

3. Built-in Exceptions in Python

Many built-in exceptions in Python catch exceptions. We can use the print(dir(locals()['__builtins__'])) command to see the built-in exceptions in Python.

The table below is a list of some common built-in exceptions in Python.

ExceptionCause of the exception
AssertionErrorReturns an exception when the comparison expression of the assert statement has a result of False
FloatingPointErrorError occurs when performing operations on floating-point values
ImportErrorOccurs when importing a module that Python cannot find
IndexErrorOccurs when accessing an element with an index outside the allowed range
KeyErrorOccurs when a key is not found in a Dictionary
KeyboardInterruptWhen users type interrupt keys (Ctrl+C or Delete)
MemoryErrorOccurs when the storage memory is full
NameErrorOccurs when a variable is not found in the local or global scope
NotImplementedErrorOccurs when an abstract method of a base class is not redefined in a derived class
OSErrorThese are system errors of the operating system
OverflowErrorOccurs when the result of a calculation gives a value too large to be stored and represented
RuntimeErrorOccurs when an exception does not belong to any pre-built exception in Python
SyntaxErrorOccurs when the syntax of Python is not correct
IndentationErrorOccurs when using indentation incorrectly
TabErrorOccurs when using tabs or inconsistent spaces
SystemErrorOccurs when the interpreter detects some internal error
TypeErrorOccurs when a method or operator is applied to an object with an inappropriate data type
UnboundLocalErrorOccurs when assigning a value (reference) to a local variable in a method but there is no value that the variable refers to
UnicodeErrorOccurs when encoding or decoding related to Unicode is corrupted
ValueErrorA function has arguments passed in the correct data type but the value of the argument is inappropriate
ZeroDivisionErrorDividing a number by 0
5/5 - (1 vote)
Previous and next lesson in subject<< Operations on Dictionary Data Structure in PythonHandling exceptions in Python >>

Leave a Reply

Your email address will not be published. Required fields are marked *