Python Errors and Exceptions

Get Ready for Your Dream Job: Click, Learn, Succeed, Start Now!

In this article, we will learn about errors and exceptions in Python. Let’s start with their definitions.

What are errors?

The problems due to which the execution of a program terminates are known as errors. On the other hand, when an internal event changes the normal flow of the program it is known as an error.

There are two types of errors:

1. Syntax errors

2. Logical errors(exceptions)

1. Syntax errors in Python

We often come across errors while writing and executing programs. The errors as a result of not following proper structure are known as the syntax error or parsing errors. Examples of syntax errors include ,missing the : in the if statement or not importing the libraries properly and so on.

Example of syntax errors:

If 2>1 print(“@”)

The output of the above line of code will be an error as follows:

if 2>1 print(“2”)
^
SyntaxError: invalid syntax

Example

amount=1000
if(amount>500)
    print("eligble")

Output:

File “main.py”, line 5
if(amount>500)
^
SyntaxError: invalid syntax
** Process exited – Return Code: 1 **
Press Enter to exit terminal

2. Logical errors(Exception) in Python

During the runtime, the errors that occur after passing the syntax test are called logical errors. For example, when we divide any number by zero, the error that is raised is known as ZeroDivisionError. The error that occurs when we import a module that does not exist is known as ImportError.

For example the following code gives a ZeroDivisionError

marks=1000
a=marks/0
print(a)

Output

Traceback (most recent call last):
File “C:\Users\qures\.spyder-py3\myfirstcode.py”, line 10, in <module> a=marks/0
ZeroDivisionError: division by zero

Example: when indentation is incorrect, we get indentation error.

if(a>3):
print(“gfg”)

Output

print(“gfg”)
^
IndentationError: expected an indented block

Semantic Errors in Python

These are caused when there are errors in logic. Here the code will execute without any issues but the results will not be as you expect.

These errors are most of the time difficult to locate and fix.

Assertion Errors in Python

Instead of waiting for an error message after the execution of the code we can also start off by declaring an assertion in python. We assert that if the condition is true then the code can continue execution but in case the assertion is false the program throws an AssertionError exception.

For example, look at the following piece of code:

import sys
assert ('mac' in sys.platform), "This code runs on mac only."

When executed the above code gives the following AssertionError:

Output

assert (‘mac’ in sys.platform), “This code runs on mac only.”
AssertionError: This code runs on mac only.

Python in-built exceptions

1. Assertion error

This raises on failure of an assert statement. Also known as python raise expression.

Example:

assert(1==1)
assert(1==2)

Output:

Traceback (most recent call last):
File “main.py”, line 5, in <module>
assert(1==2)
AssertionError
** Process exited – Return Code: 1 **
Press Enter to exit terminal

2. attributeError in Python

Occurs in failure of an attribute assignment or reference.

Example:

x=10
x.append(6)

Output:

Traceback (most recent call last):
File “main.py”, line 9, in <module>
X.append(6)
AttributeError: ‘int’ object has no attribute ‘append’
** Process exited – Return Code: 1 **
Press Enter to exit terminal

3. EOFError in python

Raises when your input() reaches the condition for end-of-file.

4. FloatingPoint Error in python

Raises in the failure of a floating point operation.

5. GeneratorExit in Python

Raises on the calling of a generators close() method

6. ImportError in python

Raises when you import an unknown module

Example

From math import ppi 

Output:

Traceback (most recent call last):
File “main.py”, line 6, in <module>
from math import ppi
ImportError: cannot import name ‘ppi’ from ‘math’ (/usr/lib/python3.8/lib-dynload/math.cpython-38-x86_64-linux-gnu.so)
** Process exited – Return Code: 1 **
Press Enter to exit terminal

7. IndexError in python

Raises on accessing an index in a sequence that i out of range

Example:

list=[1,2,3,5]
print(list[6])

Output:

Traceback (most recent call last):
File “main.py”, line 7, in <module>
print(list[6])
IndexError: list index out of range
** Process exited – Return Code: 1 **
Press Enter to exit terminal

8. KeyError in python

Raises when key cannot be found in the declared dictionary

Example:

dict={1:'jelly',2:'bean'}
print(dict[3])

Output:

Traceback (most recent call last):
File “main.py”, line 7, in <module>
print(dict[3])
KeyError: 3
** Process exited – Return Code: 1 **
Press Enter to exit terminal

9. KeyboardInterrupt in python

Raises when the user accidentally hits the interrupt key(Ctrl+C)

10. memoryError in python

Raises when any operation has insufficient memory space

11. ModuleNotFoundError in python

Raises when you try to import a module that does not exist.

Example:

Import maths

Output:

Traceback (most recent call last):
File “main.py”, line 1, in <module>
import maths
ModuleNotFoundError: No module named ‘maths’
** Process exited – Return Code: 1 **
Press Enter to exit terminal

12. NameError in python

Raises when name not found within the scope

Example

Apple

Output:

Traceback (most recent call last):
File “main.py”, line 1, in <module>
apple
NameError: name ‘apple’ is not defined
** Process exited – Return Code: 1 **
Press Enter to exit terminal

13. NotImplementedError in python

Raises with an abstract method

14. OSError in python

Raises due to system related error by the system operation

15. OverflowError in python

Raises when the result of an arithmetic operation is too huge to represent

16. ReferenceError in python

Raises on using a weak reference proxy to access a garbage collection referent

17. runtimeError in python

When the error does not fall in any of the above specific categories it raises a runtime error

18. stopIteration in python

Raises by the next() function to indicate that the iterator cannot return any items further

Example:

y = [1, 2, 3]
x = iter(y)
print(x.__next__())
print(x.__next__())
print(x.__next__())
print(x.__next__())

Output:

1
2
3
Traceback (most recent call last):
File “main.py”, line 6, in <module>
print(x.__next__())
StopIteration** Process exited – Return Code: 1 **
Press Enter to exit terminal

19. IndentationError in python

Raises when the indentation is incorrect

20. TabError in python

Raises if there is inconsistency in in indentation of tabs and spaces

21. SystemError in python

Raises on the detection of an internal error

22. systemExit in python

sys.exit() raises the SystemExit exception

23. TypeError in python

Raises on the application of method or attribute to an object of type incorrect

Example:

'10'+10

Output:

Traceback (most recent call last):
File “main.py”, line 1, in <module>
’10’+10
TypeError: can only concatenate str (not “int”) to str** Process exited – Return Code: 1 **
Press Enter to exit terminal

24. UnboundLocalError in python

Raise when you try to get access to local variables without first initialising its value.

Example:

var = 20 

def my_function():
    print(var)
    var = 'Hello' 
    print(var)

my_function() 

Output:

Traceback (most recent call last):
File “main.py”, line 8, in <module>
my_function() # Calling function
File “main.py”, line 4, in my_function
print(var)
UnboundLocalError: local variable ‘var’ referenced before assignment** Process exited – Return Code: 1 **
Press Enter to exit terminal

25. UnicodeError in python

Raises when you raise exceptions relating to unicode encoding and decoding occur.

26. ValueError in python

Raises when you send an argument of the correct type but the value is not proper.

Example:

x=int(input("print integer"))

Output:

print integer
12.4
Traceback (most recent call last):
File “main.py”, line 1, in <module>
x=int(input(“print integer”))
ValueError: invalid literal for int() with base 10: ‘12.4’** Process exited – Return Code: 1 **
Press Enter to exit terminal

Example of python in-built exceptions:

Type of Exception Cause of error 
Assertionerror  Raised when assert statement fail
Attributeerror  Raised when attribute assignment or reference fail
EOFerror Raised when the input() function hits end- of-file condition. 
FloatingPointError Raised when a floating point operation fails
GeneratorExit  Raised when a generator’s close() method is called.
ImportError  Raised when the imported module is not found. 
IndexError  Raised when index of a sequence is out of range 
KeyError  Raise when key is not found in the dictionary data structure
KeyboardInterrupt Raised on the hitting of the interrupt key by user(Ctrl+c and Delete)
MemoryError Raised when an operation is out of memory storage
NameError Raised when variable is not located globally or locally
NotImplementedError Raised by the abstract methods
OSError Raised when there is an operating system related system error
OverflowError Raised when the end result of any arithmetic operation is too large to be printed
ReferenceError  Raised when a weak frequency proxy is used to access a garbage collected referent 
RuntimeError Raised when an error does not fall in any of the categories 
StopIteration Raised by next() function to indicate that there is no next item for the iterator to return 
SyntaxError Raised due to incorrect syntax by the user
IndentationError  Raised when the indentation between the lines of code is not proper
TabError Raised when the indentation is made of inconsistent tabs and spaces
SystemError Raised when the interpreter detects an internal error in the system
SystemExit  Raised by the sys.exit() function
TypeError  Raised when a function or operation is applied to an object of incorrect type
UnboundLocalError  Raised when a reference is made to a local variable within the function but there is no value bound to the variable 
UnicodeError Raised when an error related to encoding and decoding a unicode occurs
UnicodeEncodeError  Raised when unicode related error occurs during encoding 
UnicodeDecodeError  Raised when unicode related error occurs during decoding 
UnicodeTranslateError  Raised when a  unicode related error occurs during translating 
ValueError  Raised when a function gets an argument of correct type but improper value 
ZeroDivisionError  Raised when the second operand of division or modulo operation is zero

Python Error and Python Exception message

A four line message is printed on the screen when an exception occurs in python and it is not handled.

1. The firstline states that it is a traceback. Meaning that the interpreter traces back the error to its exact source.

2. The second tells us the exact line numbers in the lines of code which has caused this error.

3. The third line tells which line or statement is causing the error.

4. Lastly, the fourth line tells us the type of exception that has occurred. We have seen a number of exceptions in the above sub topics and your errors would likely fall in one of these categories. Based on the type of error the programmer can locate the line causing the error and work towards fixing the error.

5. A short description is also given to tell the user of what exactly went wrong.

User-defined exceptions in Python

Programmers can also define specific exceptions exclusively for the piece of code. These exceptions are called user defined exceptions. We handle these exceptions using the try, finally and except clauses.

Catching exception in python

Exceptions in python code can occur due to a variety of reasons. As a software developer you must code in a manner that an occurrence of an exception should be well handled so it leads to less corrupt code.

Python contains a very self-reliant and robust error handling framework. It uses structured exception handling and a set of predefined exceptions. Programs can detect the time of error during run time and act accordingly. Handling exceptions include methods such as changing the code, opting another path to execute, using default values, encouraging for correct input.

Error handling in Python

Handling methods are used to handle errors in the code. In the case of encountering an error or exception, we use error handling methods to solve the issue.

1. Handling exception with try/except/finally

try/except/finally are the most common block to handle errors. Try block contains all the unsafe code, except contains fall back code and final code is written in finally block.

Example:

try:
    print("code starts")
    pritn(2/0)
except:
    print('error error error')
finally:
    print('pythongeeks')

Output:

code starts
error error error
pythongeeks** Process exited – Return Code: 0 **
Press Enter to exit terminal

2. Raising exceptions for predefined exceptions

We raise an exception when we want to code for only certain conditions. This is done mostly in banks or places where online transactions take place so the situations must be taken care of.

Example:

try:
    amount=1000
    if amount<2000:
        raise ValueError("add money")
    else:
        print("eligible")
except ValueError as e:
    print(e)

Output:

add money
** Process exited – Return Code: 0 **
Press Enter to exit terminal

Conclusion

In this article, we had a look at the syntax and logical errors. We then looked at a few examples and then finally we learned about the python in-built exceptions. We hope our explanation was easy to understand.

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google | Facebook


PythonGeeks Team

The PythonGeeks Team offers industry-relevant Python programming tutorials, from web development to AI, ML and Data Science. With a focus on simplicity, we help learners of all backgrounds build their coding skills.

Leave a Reply

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