Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Python Pickling and Exception Handling (2)

The document explains Python's pickle module for serializing and deserializing Python object structures, detailing the processes of pickling and unpickling. It also covers exception handling in Python, including standard exception classes, handling techniques, and the use of try-except and try-finally blocks. Additionally, it emphasizes the importance of managing exceptions to maintain program flow and includes examples of common exceptions.

Uploaded by

Gautham J K
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Pickling and Exception Handling (2)

The document explains Python's pickle module for serializing and deserializing Python object structures, detailing the processes of pickling and unpickling. It also covers exception handling in Python, including standard exception classes, handling techniques, and the use of try-except and try-finally blocks. Additionally, it emphasizes the importance of managing exceptions to maintain program flow and includes examples of common exceptions.

Uploaded by

Gautham J K
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Module -IV

Python Pickling
Python Pickling
• Python pickle module is used for serializing and de-serializing
python object structures.

• Pickling: The process to converts any kind of python objects (list,


dict, etc.) into byte streams (0s and 1s) is called pickling or
serialization or flattening or marshalling.

• Unpickling: converts the byte stream (generated through


pickling) back into python objects by a process called as
unpickling.
Why Pickle?
• allow us to easily transfer data from one server/system to another
and then store it in a file or database

• Precaution:
• advisable not to unpickle data received from an untrusted source as they may
pose security threat

• Only after importing pickle module we can do pickling and unpickling


import pickle
Pickling
Pickle a simple list: Pickle_list1.py

import pickle
mylist = ['a', 'b', 'c', 'd']
with open('datafile.txt', 'wb') as fh:
pickle.dump(mylist, fh)
Unpickle
• Unpickle a simple list: unpickle_list1.py

import pickle
pickle_off = open ("datafile.txt", "rb")
emp = pickle.load(pickle_off)
print(emp)
Unpickle
Pickling
Python - Exceptions
Python - Exceptions
• An exception is an event, which occurs during the execution of a
program that disrupts the normal flow of the program's instructions.

• In general, when a Python script encounters a situation that it cannot


cope with, it raises an exception.

• An exception is a Python object that represents an error.

• When a Python script raises an exception, it must either handle the


exception immediately otherwise it terminates and quits.
Python - Exceptions Handling
• Python provides two very important features to handle any
unexpected error in your Python programs and to add debugging
capabilities in them
• Exception Handling
• Assertions
Standard Exception Classes
• Exception
• Base class for all exceptions

• ArithmeticError
• Base class for all errors that occur for numeric calculation

• ZeroDivisionError
• Raised when division or modulo by zero takes place for all numeric types

• AttributeError
• Raised in case of failure of attribute reference or assignment.
• X = 10
• # Raises an AttributeError
• X.append(6)
Standard Exception examples
• KeyboardInterrupt
• Raised when the user interrupts program execution, usually by pressing Ctrl+c.
• IndexError
• Raised when an index is not found in a sequence.
• KeyError
• Raised when the specified key is not found in the dictionary.
• NameError
• Raised when an identifier is not found in the local or global namespace.
• geek = input()
• print(geeky)
Standard Exception examples
• IOError
• Raised when an input/ output operation fails, such as open() function when
trying to open a file that does not exist.
• SyntaxError
• Raised when there is an error in Python syntax.
• IndentationError
• Raised when indentation is not specified properly.
• RuntimeError
• Raised when a generated error does not fall into any category.
Handling an exception
• If you have some suspicious code that may raise an exception, you can
defend your program by placing the suspicious code in a try: block.

• After the try: block, include an except: statement, followed by a


block of code which handles the problem as elegantly as possible.
try-except Examples
Handling an Exception
• try-except
• except Clause with single Exceptions
• except Clause with multiple Exceptions

• try-finally clause
Handling an exception
The except Clause with Multiple Exceptions
The try-finally Clause
• You can use a finally: block along with a try: block.
• The finally block is a place to put any code that must execute,
whether the try-block raised an exception or not
The try-finally Clause
The try-finally Clause
• You cannot use else clause as well along with a finally clause.
The try-finally clause
try:
try:
with open("demo.txt", “r") as file:
data = file.readlines()
for line in data:
word = line.split()
print (word)
finally:
print("this should be executed")
except IOError:
print("Error") You cannot use else clause as well along with a finally clause.
else:
print("No Error")
The try-finally clause
• When an exception is thrown in the try block, the execution
immediately passes to the finally block.

• After all the statements in the finally block are executed, the
exception is raised again and is handled in the except statements if
present in the next higher layer of the try-except statement.
Argument of an Exception
• An exception can have an argument, which is a value that gives
additional information about the problem.
• The contents of the argument vary by exception.
• You capture an exception's argument by supplying a variable in the
except clause as follows
Argument of an Exception

You might also like