Python Unit - IV
Python Unit - IV
UNIT - IV
Error Handling:
Python Errors
Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are the
problems in a program due to which the program will stop the execution. On the other hand,
exceptions are raised when some internal events occur which changes the normal flow of the
program.
Exceptions:
Exceptions are raised when the program is syntactically correct but the code resulted in
an error. This error does not stop the execution of the program, however, it changes the normal
flow of the program.
Example:
marks = 10000
a = marks / 0 #Exceptions - ZeroDivisionError
print(a)
Common Exceptions
Python provides the number of built-in exceptions, but here we are describing the
common standard exceptions. A list of common exceptions that can be thrown from a standard
Python program is given below.
✓ ZeroDivisionError: Occurs when a number is divided by zero.
✓ NameError: It occurs when a name is not found. It may be local or global.
✓ IndentationError: If incorrect indentation is given.
Exception
1
Base class for all exceptions
StopIteration
2
Raised when the next() method of an iterator does not point to any object.
SystemExit
3
Raised by the sys.exit() function.
StandardError
4
Base class for all built-in exceptions except StopIteration and SystemExit.
ArithmeticError
5
Base class for all errors that occur for numeric calculation.
OverflowError
6
Raised when a calculation exceeds maximum limit for a numeric type.
FloatingPointError
7
Raised when a floating point calculation fails.
ZeroDivisionError
8
Raised when division or modulo by zero takes place for all numeric types.
AssertionError
9
Raised in case of failure of the Assert statement.
AttributeError
10
Raised in case of failure of attribute reference or assignment.
EOFError
11 Raised when there is no input from either the raw_input() or input() function and the end of file is
reached.
ImportError
12
Raised when an import statement fails.
KeyboardInterrupt
13
Raised when the user interrupts program execution, usually by pressing Ctrl+c.
LookupError
14
Base class for all lookup errors.
IndexError
15
Raised when an index is not found in a sequence.
KeyError
16
Raised when the specified key is not found in the dictionary.
NameError
17
Raised when an identifier is not found in the local or global namespace.
UnboundLocalError
18 Raised when trying to access a local variable in a function or method but no value has been
assigned to it.
EnvironmentError
19
Base class for all exceptions that occur outside the Python environment.
IOError
20 Raised when an input/ output operation fails, such as the print statement or the open() function
when trying to open a file that does not exist.
IOError
21
Raised for operating system-related errors.
SyntaxError
22
Raised when there is an error in Python syntax.
IndentationError
23
Raised when indentation is not specified properly.
SystemError
24 Raised when the interpreter finds an internal problem, but when this error is encountered the
Python interpreter does not exit.
SystemExit
25 Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code,
causes the interpreter to exit.
TypeError
26
Raised when an operation or function is attempted that is invalid for the specified data type.
ValueError
27 Raised when the built-in function for a data type has the valid type of arguments, but the arguments
have invalid values specified.
RuntimeError
28
Raised when a generated error does not fall into any category.
NotImplementedError
29 Raised when an abstract method that needs to be implemented in an inherited class is not actually
implemented.
Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and generate
an error message.
Department of CS&IT, S.S.D.M College. 3
Python: Unit - IV
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.
Syntax:
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
➢ A single try statement can have multiple except statements. This is useful when
the try block contains statements that may throw different types of exceptions.
➢ You can also provide a generic except clause, which handles any exception.
➢ After the except clause(s), you can include an else-clause. The code in the else-
block executes if the code in the try: block does not raise an exception.
➢ The else-block is a good place for code that does not need the try: block's
protection.
Example:
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
# Throws error
print ("Fourth element = %d" %(a[3]) )
except IndexError:
print ("An error occurred")
A try statement can have more than one except clause, to specify handlers for different
exceptions. Please note that at most one handler will be executed.
Example:
try :
a=3
if a < 4 :
# throws ZeroDivisionError for a = 3
b = a/(a-3)
# throws NameError if a >= 4
print ("Value of b = ", b)
except(ZeroDivisionError, NameError):
print ("\nError Occurred and Handled")
Else Clause
In python, can also use else clause on the try-except block which must be present after
all the except clauses. The code enters the else block only if the try clause does not raise an
exception.
Example:
def AbyB(a , b):
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)
Finally Keyword
Python provides a keyword finally, which is always executed after try and except
blocks. The finally block always executes after normal termination of try block or after try
block terminates due to some exception.
Syntax:
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
Example:
try:
k = 5//0 # raises divide by zero exception.
print(k)
except ZeroDivisionError:
print("Can't divide by zero")
finally:
print('This is always executed')
Raising Exception
The raise statement allows the programmer to force a specific exception to occur. The
sole argument in raise indicates the exception to be raised. This must be either an exception
instance or an exception class (a class that derives from Exception).
Syntax:
raise ExceptionType("Error message")
In this syntax, ExceptionType is the type of exception you want to raise, and "Error
message" is an optional error message that provides additional information about the exception.
Example:
age = -5
if age < 0:
raise ValueError("Age cannot be negative")
In this example, we check if the age variable is negative, and if it is, we raise a
ValueError exception with the error message "Age cannot be negative".
Raise an exception without error message like this,
raise ValueError
Raise an exception using try catch block like this,
Example:
age = -5
try:
if age < 0:
raise ValueError("Age cannot be negative")
except ValueError:
print("Age Error")
Raising exceptions can be useful when you want to indicate that something has gone
wrong in your code. It allows you to interrupt the normal flow of execution and handle the
error in a controlled way.
Data Streams
A data stream refers to a continuous flow of data that is read from or written to a data
source or destination in a sequential manner. Data streams can be of various types, including
file streams, network streams, standard input/output streams, and more.
File Streams:
File streams allow reading from or writing to files on disk. Python's built-in open()
function is used to open file streams in various modes, such as read mode ("r"), write mode
("w"), append mode ("a"), binary mode ("b"), etc.
Network Streams:
Network streams enable communication over computer networks using protocols like
TCP/IP and UDP. Python's socket module provides support for creating client and server
sockets to send and receive data over networks.
Third-party Libraries:
Various third-party libraries in Python offer higher-level abstractions for working with
data streams, such as requests for HTTP requests, pandas for data manipulation, paramiko for
SSH connections, pyserial for serial communication, and more. These libraries provide
convenient interfaces and additional functionality for specific use cases.
Use Cases:
✓ Data Processing: Reading data from sensors, logs, or other sources for
processing, analysis, or visualization.
✓ Communication: Sending and receiving data over networks for client-server
communication, web scraping, API requests, etc.
✓ Data Storage: Writing data to files or databases for storage and retrieval.
✓ Data Integration: Integrating data streams from multiple sources or systems
for aggregation, transformation, or synchronization.
open Function
➢ The key function for working with files in Python is the open() function.
➢ The open() function takes two parameters; filename, and mode.
➢ There are four different methods (modes) for opening a file.
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
Syntax:
file object = open(file_name [, access_mode][, buffering])
➢ file_name − The file_name argument is a string value that contains the name of the file
that you want to access.
➢ access_mode − The access_mode determines the mode in which the file has to be
opened, i.e., read, write, append, etc. A complete list of possible values is given below
in the table. This is optional parameter and the default file access mode is read (r).
➢ buffering − If the buffering value is set to 0, no buffering takes place. If the buffering
value is 1, line buffering is performed while accessing a file. If you specify the buffering
value as an integer greater than 1, then buffering action is performed with the indicated
buffer size. If negative, the buffer size is the system default.
r
1 Opens a file for reading only. The file pointer is placed at the beginning
of the file. This is the default mode.
rb
2 Opens a file for reading only in binary format. The file pointer is placed
at the beginning of the file. This is the default mode.
r+
3 Opens a file for both reading and writing. The file pointer placed at the
beginning of the file.
rb+
4 Opens a file for both reading and writing in binary format. The file pointer
placed at the beginning of the file.
w
5 Opens a file for writing only. Overwrites the file if the file exists. If the
file does not exist, creates a new file for writing.
wb
6 Opens a file for writing only in binary format. Overwrites the file if the
file exists. If the file does not exist, creates a new file for writing.
w+
Opens a file for both writing and reading. Overwrites the existing file if
7
the file exists. If the file does not exist, creates a new file for reading and
writing.
wb+
Opens a file for both writing and reading in binary format. Overwrites the
8
existing file if the file exists. If the file does not exist, creates a new file
for reading and writing.
a
Opens a file for appending. The file pointer is at the end of the file if the
9
file exists. That is, the file is in the append mode. If the file does not exist,
it creates a new file for writing.
ab
Opens a file for appending in binary format. The file pointer is at the end
10
of the file if the file exists. That is, the file is in the append mode. If the
file does not exist, it creates a new file for writing.
a+
Opens a file for both appending and reading. The file pointer is at the end
11
of the file if the file exists. The file opens in the append mode. If the file
does not exist, it creates a new file for reading and writing.
ab+
Opens a file for both appending and reading in binary format. The file
12
pointer is at the end of the file if the file exists. The file opens in the append
mode. If the file does not exist, it creates a new file for reading and writing.
file.closed
1
Returns true if file is closed, false otherwise.
file.mode
2
Returns access mode with which file was opened.
file.name
3
Returns name of the file.
file.softspace
4
Returns false if space explicitly required with print, true otherwise.
Example:
f = open("testFile.txt")
print "Name of the file: ", f.name
print "Closed or not : ", f.closed
print "Opening mode : ", f.mode
print "Softspace flag : ", f.softspace
f.close()
Open a File
To open the file, use the built-in open() function.
The open() function returns a file object, which has a read() method for reading the
content of the file.
Example:
f = open("textfile.txt", "r")
print(f.read())
If the file is located in a different location, need to specify the file path,
f = open("D:\\myfiles\textfile.txt", "r")
print(f.read())
Read Lines
Return one line by using the readline() method
Example:
f = open("textfile.txt", "r")
print(f.readline())
By looping through the lines of the file, can read the whole file, line by line.
Example:
f = open("textfile.txt", "r")
for x in f:
print(x)
Delete a File
To delete a file, you must import the OS module, and run its os.remove() function.
Python os module provides methods that help you perform file-processing operations, such as
renaming and deleting files.
Example:
import os
os.remove("textfile.txt")
Creating Pipe
To create a pipe in Python, you can use the subprocess.Popen class with the
stdin=subprocess.PIPE, stdout=subprocess.PIPE, or stderr=subprocess.PIPE arguments to
specify that a pipe should be created for the standard input, output, or error streams,
respectively.
Example:
import subprocess
# Create a subprocess with a pipe for stdin
child_process = subprocess.Popen(["python", "child_process.py"],
stdin=subprocess.PIPE)
Example:
# Close the pipe after writing data
child_process.stdin.close()
Error Handling:
Always handle exceptions, such as BrokenPipeError, IOError, or
subprocess.CalledProcessError, when working with pipes to ensure robustness and reliability.
Use Cases:
➢ Interprocess communication (IPC) between Python scripts or external
programs.
➢ Implementing producer-consumer patterns, where one process produces data
and another consumes it.
➢ Building data processing pipelines, where data flows from one process to
another for transformation or analysis.
Handling IO Exceptions
Handling IO (Input/Output) exceptions in Python is essential for ensuring that your
code gracefully handles errors related to reading from or writing to files, network connections,
or other IO operations. These exceptions can occur due to various reasons, such as file not
found, permission denied, network errors, and so on. Proper error handling helps in making
your code more robust and reliable.
Common IO Exceptions:
✓ FileNotFoundError: Raised when a file or directory is not found.
✓ PermissionError: Raised when permission is denied while trying to access a file
or directory.
✓ IOError: Base class for IO-related errors.
✓ OSError: Base class for operating system-related errors.
Handling IO exceptions appropriately ensures that your code can gracefully recover
from errors and handle exceptional conditions, leading to more reliable and robust applications.
Directories
Directories in Python involves tasks such as creating, listing, navigating, and deleting
directories. Python's built-in os and os.path modules provide functions for interacting with
directories and paths.
Creating Directories:
You can create a directory using the os.makedirs() function. This function creates all
intermediate-level directories if they don't exist.
Example:
import os
# Create a directory
os.makedirs("my_directory")
Directory Exists:
You can check if a directory exists using the os.path.exists() function.
Example:
# Check if directory exists
if os.path.exists("my_directory"):
print("Directory exists")
else:
print("Directory does not exist")
Change Directory:
You can change the current working directory using the os.chdir() function.
Example:
# Change current working directory
os.chdir("my_directory")
Remove Directory:
You can remove a directory using the os.rmdir() function. Note that the directory must
be empty for this function to succeed.
Example:
# Remove directory
os.rmdir("my_directory")
Other Operations:
➢ Getting the Current Working Directory: Use os.getcwd() to get the current
working directory.
➢ Joining Paths: Use os.path.join() to join directory and file names into a single
path.
➢ Splitting Paths: Use os.path.split() to split a path into directory and file name
components.
➢ Checking if a Path is a Directory: Use os.path.isdir() to check if a path refers to
a directory.
Working with directories in Python is straightforward using the os and os.path modules.
These modules provide a wide range of functions for performing various directory-related
operations, making it easy to manage directories in your Python programs.