0% found this document useful (0 votes)
10 views7 pages

Python Exception Handling & Collections

This document covers exception handling and collections in Python, explaining the difference between syntax errors and exceptions, and how to handle exceptions using try and except blocks. It also introduces the Python collections module, detailing various collection types such as namedtuple, OrderedDict, defaultdict, Counter, and deque, along with their functionalities. Additionally, it discusses the characteristics of Python sets and how to create them.

Uploaded by

krushnadongare91
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views7 pages

Python Exception Handling & Collections

This document covers exception handling and collections in Python, explaining the difference between syntax errors and exceptions, and how to handle exceptions using try and except blocks. It also introduces the Python collections module, detailing various collection types such as namedtuple, OrderedDict, defaultdict, Counter, and deque, along with their functionalities. Additionally, it discusses the characteristics of Python sets and how to create them.

Uploaded by

krushnadongare91
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit – III

Exception Handling and Collections

Python Exceptions
When a Python program meets an error, it stops the execution of the rest of the program.
An error in Python might be either an error in the syntax of an expression or a Python
exception. We will see what an exception is. Also, we will see the difference between a
syntax error and an exception in this tutorial. Following that, we will learn about trying and
except blocks and how to raise exceptions and make assertions. After that, we will see
the Python exceptions list.

What is an Exception?
An exception in Python is an incident that happens while executing a program that causes
the regular course of the program's commands to be disrupted. When a Python code
comes across a condition it can't handle, it raises an exception. An object in Python that
describes an error is called an exception.

When a Python code throws an exception, it has two options: handle the exception
immediately or stop and quit.

Exceptions versus Syntax Errors


When the interpreter identifies a statement that has an error, syntax errors occur. Consider
the following scenario:

Code

1. #Python code after removing the syntax error


2. string = "Python Exceptions"
3.
4. for s in string:
5. if (s != o:
6. print( s )
Output:

if (s != o:
^
SyntaxError: invalid syntax

Role Exception is a custom exception created automatically


by OutSystems from each role available in your module. For example, if you
create a role named BackofficeUser in a module, OutSystems automatically
creates a Role Exception named Not BackofficeUser in the same module.
Exception handling in Python
Before going into the topic, we need to understand about errors and exceptions in
python and the difference between these two words.

First things first, there are errors-two types of them - Syntax errors and logical errors.
A syntax error occurs when the programmer did not follow the predefined syntax rules of
a particular entity in the code.

If the compiler finds a syntax mistake, it terminates the program and raises the
error. We need to fix it.

Logical errors are the mistakes the programmer makes in the logic of the code. These
are not raised; instead, the mistake is to be understood when the code does not meet
the purpose or problem. These are to be searched, found, and edited by the programmer
and are hard to find.

Now coming to the concept of exceptions:

An exception is an unexpected error raised at the time of execution (not at


compilation). These are not dangerous to the code; there are methods in python to
handle these exceptions.

Example: If we try to divide a number by 0, the compiler won't detect it as the syntax is
correct. At the time of execution, the exception will be raised.

Code:

1. a = 3
2. print(a/0)
Output:

Traceback (most recent call last):


File "D:\Programs\python\exception_ex.py", line 2, in
print(a/0)
ZeroDivisionError: division by zero

The "Exception" is the base class for all the exceptions. There is a whole exception
hierarchy defined in python. You can check it out online.

We can handle exceptions using try and except blocks. We can also raise user-defined
exceptions, which will be discussed further in the article.

Using try and except statements to catch exceptions:


Exceptions usually occur unexpectedly and disturb the execution of the whole
code. Hence, we catch these exceptions and handle them for the execution to go
smoothly.

And how do we do that?


o The part of the code on which the programmer doubts that it may cause an
exception is kept in the try block.
o If the doubt comes true and an exception is found, we write the handling code inside
the "except" block.
o What happens here is that the code we write inside the "except" block replaces
the exception/error message that usually gets printed when the exception is found.
o In this way, the execution flow is not disturbed, and the exception is handled.
Syntax:

1. try:
2. #Code that might raise an exception
3. except:
4. #Code to replace the exception message

EXCEPTON CONTEXT

1. ZeroDivisionError If we try to perform division by 0

If the result of an operation is too big to be


2. OverflowError
presented

If we try to access an index of a sequence that is


3. IndexError
invalid

If we try to call an attribute (function object), its


4. AttributeError
type is unsupported.

If a function in python reaches the end of the file


5. EOFError
without reading any data at all.

If we try to access a key in a dictionary that is


6. KeyError
invalid or does not even exist

7. IOError If we give a wrong file name or incorrect location.

To catch a particular Exception (try with multiple except


statements)
Suppose the code has a chance of raising multiple exceptions. The programmer needs to
replace different exceptions with different code, i.e., if they want to handle each
exception differently, there is an option for this too.

o One try statement can have multiple catch statements.


o We can catch a particular type of exception by mentioning the exception beside except
in the except block.

Python Collection Module


The Python collection module is defined as a container that is used to store collections of
data, for example - list, dict, set, and tuple, etc. It was introduced to improve the
functionalities of the built-in collection containers.

Python collection module was first introduced in its 2.4 release.

There are different types of collection modules which are as follows:

namedtuple()
The Python namedtuple() function returns a tuple-like object with names for each position
in the tuple. It was used to eliminate the problem of remembering the index of each field
of a tuple object in ordinary tuples.

Examples

1. pranshu = ('James', 24, 'M')


2. print(pranshu)
Output:

('James', 24, 'M')


OrderedDict()
The Python OrderedDict() is similar to a dictionary object where keys maintain the order
of insertion. If we try to insert key again, the previous value will be overwritten for that key.

Example

1. import collections
2. d1=[Link]()
3. d1['A']=10
4. d1['C']=12
5. d1['B']=11
6. d1['D']=13
7.
8. for k,v in [Link]():
9. print (k,v)
Output:

A 10
C 12
B 11
D 13
defaultdict()
The Python defaultdict() is defined as a dictionary-like object. It is a subclass of the built-
in dict class. It provides all methods provided by dictionary but takes the first argument as
a default data type.

Example

1. from collections import defaultdict


2. number = defaultdict(int)
3. number['one'] = 1
4. number['two'] = 2
5. print(number['three'])
Output:

0
Counter()
The Python Counter is a subclass of dictionary object which helps to count hashable
objects.

Example

1. from collections import Counter


2. c = Counter()
3. list = [1,2,3,4,5,7,8,5,9,6,10]
4. Counter(list)
5. Counter({1:5,2:4})
6. list = [1,2,4,7,5,1,6,7,6,9,1]
7. c = Counter(list)
8. print(c[1])
Output:

3
deque()
The Python deque() is a double-ended queue which allows us to add and remove
elements from both the ends.

Example

1. from collections import deque


2. list = ["x","y","z"]
3. deq = deque(list)
4. print(deq)
Output:

deque(['x', 'y', 'z'])


Chainmap Objects
A chainmap class is used to groups multiple dictionary together to create a single list.
The linked dictionary stores in the list and it is public and can be accessed by the map
attribute. Consider the following example.

Example

1. from collections import ChainMap


2. baseline = {'Name': 'Peter', 'Age': '14'}
3. adjustments = {'Age': '14', 'Roll_no': '0012'}
4. print(list(ChainMap(adjustments, baseline)))
Output:

['Name', 'Age', 'Roll_no' ]


UserDict Objects
The UserDict behaves as a wrapper around the dictionary objects. The dictionary can be
accessed as an attribute by using the UserDict object. It provides the easiness to work
with the dictionary.

It provides the following attribute.

data - A real dictionary used to store the contents of the UserDict class.

UserList Objects
The UserList behaves as a wrapper class around the list-objects. It is useful when we want
to add new functionality to the lists. It provides the easiness to work with the dictionary.

It provides the following attribute.

data - A real list is used to store the contents of the User class.

UserString Objects
The UserList behaves as a wrapper class around the list objects. The dictionary can be
accessed as an attribute by using the UserString object. It provides the easiness to work
with the dictionary.

It provides the following attribute.

data - A real str object is used to store the contents of the UserString class.

Python Set
A Python set is the collection of the unordered items. Each element in the set must be
unique, immutable, and the sets remove the duplicate elements. Sets are mutable which
means we can modify it after its creation.
Unlike other collections in Python, there is no index attached to the elements of the set,
i.e., we cannot directly access any element of the set by the index. However, we can print
them all together, or we can get the list of elements by looping through the set.

Creating a set
The set can be created by enclosing the comma-separated immutable items with the curly
braces {}. Python also provides the set() method, which can be used to create the set by
the passed sequence.

Example 1: Using curly braces


1. Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sun
day"}
2. print(Days)
3. print(type(Days))
4. print("looping through the set elements ... ")
5. for i in Days:
6. print(i)
Output:

{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'}


<class 'set'>
looping through the set elements ...
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday

Common questions

Powered by AI

An exception in Python is an incident that happens during the execution of a program and disrupts its normal flow. Exceptions occur when a particular condition arises that the program cannot handle, and they are not detected by the compiler as syntax errors . In contrast, a syntax error is identified by the interpreter when it encounters a statement that doesn't adhere to the language's syntax rules. This leads to immediate termination of the program when syntax errors are found during the parsing stage . A syntax error needs to be corrected for the program to execute, whereas exceptions can be handled within the code using try-except blocks, allowing the program to continue running .

A ZeroDivisionError can be raised in Python by attempting to divide a number by zero. For example, the code 'a = 3; print(a/0)' would raise a ZeroDivisionError since dividing by zero is mathematically undefined . To handle this error, a try-except block can be used: 'try: print(a/0) except ZeroDivisionError: print("Cannot divide by zero")'. This would prevent the program from crashing and output a meaningful message instead. If not properly managed, this exception would cause the program to terminate abruptly, which could lead to loss of data or an unpleasant user experience .

The concept of set uniqueness can be leveraged to efficiently solve problems involving deduplication, such as finding unique elements in a list or the union of multiple lists without duplicates. Mutability allows for dynamic addition and removal of elements, which can benefit algorithms that require altering the dataset dynamically, like active filtering. An example use case is resolving real-time inventory systems where unique identifiers form the basis for asset tracking. Using a set to track inventory IDs ensures duplicates are avoided automatically, while mutability allows new items to be added or existing items to be removed as stock levels change .

Ordered dictionaries differ from standard dictionaries in Python in that they maintain the order of keys based on when the keys were added. This means that when iterating over an OrderedDict, keys are returned in the insertion order, unlike a regular dictionary which, prior to Python 3.7, did not preserve any specific order . Practical applications that might favor their use include cases where data order is essential, such as when presenting data generated or received in a specific order, or when creating lists of attributes to output in a particular sequence .

Deque, or double-ended queue, in Python's collections module allows the addition and removal of elements from both ends efficiently, which provides a significant edge over typical lists in scenarios that require constant-time appends and pops on both ends. While lists are optimized for fast fixed-length operations and random access, deques excel in situations where elements need to be handled in a FIFO (first-in, first-out) or LIFO (last-in, first-out) manner. This makes them ideal for implementing queues and stacks with better performance than using a standard list, especially when dealing with large datasets .

User-defined exceptions in Python allow developers to create custom exceptions that are specific to their application's requirements. They enhance error handling capabilities by offering precise and clear error descriptions tailored to the context of the application, thus improving code clarity and debugging efficiency. By defining a custom exception class that inherits from the base Exception class, developers can raise it in response to specific conditions that are not covered by standard exceptions. This approach aids in communicating the nature of errors more effectively, leading to better exception management and more robust applications .

The defaultdict from Python's collections module is a subclass of the built-in dictionary class that provides a default value for a nonexistent key. Unlike a normal dictionary, where attempting to access a missing key raises a KeyError, defaultdict allows the program to continue by using a factory function to provide a default value. This is advantageous in scenarios requiring initialization of keys or aggregations, such as counting occurrences, where accessing and updating values for missing keys is frequent and should not result in errors .

ChainMap in Python provides a way to group multiple dictionaries into a single view that can be treated as a unified mapping. The primary benefit is its ability to combine multiple dictionaries without modifying or copying the original dictionaries, thus conserving memory and efficient in terms of performance. It facilitates tasks like searching across multiple dictionaries as if they were one, simplifying cases where layered data structures need to be accessed collectively. Additionally, updates are shown in real-time, reflecting changes across the mapped dictionaries instantaneously .

The try-except block in Python is used to handle exceptions that may occur during the execution of a block of code. Code that may raise an exception is placed in the 'try' block . If an exception occurs, the program control moves to the 'except' block, where the exception can be handled without the program crashing. This mechanism is useful because it allows the program to continue running smoothly even when unexpected errors occur, by providing an alternative execution path .

UserDict is a wrapper around the standard dict object. It behaves like a regular dictionary, but with additional features that allow it to be easily extended. UserDict is particularly beneficial when a programmer needs to subclass or extend dictionary functionalities, allowing for more sophisticated data management and enhancements without altering the base dict behavior. This is especially useful in applications requiring custom methods or adjustment of dictionary behavior while preserving standard dict operations for compatibility and integration .

You might also like