Thanks to visit codestin.com
Credit goes to www.tutorialsteacher.com

Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • Python - Get Started
  • What is Python?
  • Where to use Python?
  • Python Version History
  • Install Python
  • Python - Shell/REPL
  • Python IDLE
  • Python Editors
  • Python Syntax
  • Python Keywords
  • Python Variables
  • Python Data Types
  • Number
  • String
  • List
  • Tuple
  • Set
  • Dictionary
  • Python Operators
  • Python Conditions - if, elif
  • Python While Loop
  • Python For Loop
  • User Defined Functions
  • Lambda Functions
  • Variable Scope
  • Python Modules
  • Module Attributes
  • Python Packages
  • Python PIP
  • __main__, __name__
  • Python Built-in Modules
  • OS Module
  • Sys Module
  • Math Module
  • Statistics Module
  • Collections Module
  • Random Module
  • Python Generator Function
  • Python List Comprehension
  • Python Recursion
  • Python Built-in Error Types
  • Python Exception Handling
  • Python Assert Statement
  • Define Class in Python
  • Inheritance in Python
  • Python Access Modifiers
  • Python Decorators
  • @property Decorator
  • @classmethod Decorator
  • @staticmethod Decorator
  • Python Dunder Methods
  • CRUD Operations in Python
  • Python Read, Write Files
  • Regex in Python
  • Create GUI using Tkinter
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Python - Error Types

The most common reason of an error in a Python program is when a certain statement is not in accordance with the prescribed usage. Such an error is called a syntax error. The Python interpreter immediately reports it, usually along with the reason.

Example: Error
>>> print "hello"
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("hello")?

In Python 3.x, print is a built-in function and requires parentheses. The statement above violates this usage and hence syntax error is displayed.

Many times though, a program results in an error after it is run even if it doesn't have any syntax error. Such an error is a runtime error, called an exception. A number of built-in exceptions are defined in the Python library. Let's see some common error types.

The following table lists important built-in exceptions in Python.

ExceptionDescription
AssertionErrorRaised when the assert statement fails.
AttributeErrorRaised on the attribute assignment or reference fails.
EOFErrorRaised when the input() function hits the end-of-file condition.
FloatingPointErrorRaised when a floating point operation fails.
GeneratorExitRaised when a generator's close() method is called.
ImportErrorRaised when the imported module is not found.
IndexErrorRaised when the index of a sequence is out of range.
KeyErrorRaised when a key is not found in a dictionary.
KeyboardInterruptRaised when the user hits the interrupt key (Ctrl+c or delete).
MemoryErrorRaised when an operation runs out of memory.
NameErrorRaised when a variable is not found in the local or global scope.
NotImplementedErrorRaised by abstract methods.
OSErrorRaised when a system operation causes a system-related error.
OverflowErrorRaised when the result of an arithmetic operation is too large to be represented.
ReferenceErrorRaised when a weak reference proxy is used to access a garbage collected referent.
RuntimeErrorRaised when an error does not fall under any other category.
StopIterationRaised by the next() function to indicate that there is no further item to be returned by the iterator.
SyntaxErrorRaised by the parser when a syntax error is encountered.
IndentationErrorRaised when there is an incorrect indentation.
TabErrorRaised when the indentation consists of inconsistent tabs and spaces.
SystemErrorRaised when the interpreter detects internal error.
SystemExitRaised by the sys.exit() function.
TypeErrorRaised when a function or operation is applied to an object of an incorrect type.
UnboundLocalErrorRaised when a reference is made to a local variable in a function or method, but no value has been bound to that variable.
UnicodeErrorRaised when a Unicode-related encoding or decoding error occurs.
UnicodeEncodeErrorRaised when a Unicode-related error occurs during encoding.
UnicodeDecodeErrorRaised when a Unicode-related error occurs during decoding.
UnicodeTranslateErrorRaised when a Unicode-related error occurs during translation.
ValueErrorRaised when a function gets an argument of correct type but improper value.
ZeroDivisionErrorRaised when the second operand of a division or module operation is zero.

IndexError

The IndexError is thrown when trying to access an item at an invalid index.

Example: IndexError
>>> L1=[1,2,3]
>>> L1[3]
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
            
L1[3]
IndexError: list index out of range

ModuleNotFoundError

The ModuleNotFoundError is thrown when a module could not be found.

Example: ModuleNotFoundError
>>> import notamodule
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
            
import notamodule
ModuleNotFoundError: No module named 'notamodule'

KeyError

The KeyError is thrown when a key is not found.

Example: KeyError
>>> D1={'1':"aa", '2':"bb", '3':"cc"}
>>> D1['4']
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>

            
D1['4']
KeyError: '4'

ImportError

The ImportError is thrown when a specified function can not be found.

Example: ImportError
>>> from math import cube
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
            
from math import cube
ImportError: cannot import name 'cube'

StopIteration

The StopIteration is thrown when the next() function goes beyond the iterator items.

Example: StopIteration
>>> it=iter([1,2,3])
>>> next(it)
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
            
next(it)
StopIteration

TypeError

The TypeError is thrown when an operation or function is applied to an object of an inappropriate type.

Example: TypeError
>>> '2'+2
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
            
'2'+2
TypeError: must be str, not int

ValueError

The ValueError is thrown when a function's argument is of an inappropriate type.

Example: ValueError
>>> int('xyz')
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
            
int('xyz')
ValueError: invalid literal for int() with base 10: 'xyz'

NameError

The NameError is thrown when an object could not be found.

Example: NameError
>>> age
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
            
age
NameError: name 'age' is not defined

ZeroDivisionError

The ZeroDivisionError is thrown when the second operator in the division is zero.

Example: ZeroDivisionError
>>> x=100/0
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
            
x=100/0
ZeroDivisionError: division by zero

KeyboardInterrupt

The KeyboardInterrupt is thrown when the user hits the interrupt key (normally Control-C) during the execution of the program.

Example: KeyboardInterrupt
>>> name=input('enter your name')
enter your name^c
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
            
name=input('enter your name')
KeyboardInterrupt

Learn how to handle exceptions in Python in the next chapter.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.