Unit 4 - Python
Unit 4 - Python
Unit 4 - Python
UNIT - IV
ERROR HANDLING
Errors or inaccuracies in a program are often called as bugs. The process of finding and removing
errors is called debugging. Errors can be categorized into three major groups:
Syntax errors
Python will find these kinds of errors when it tries to parse your program, and exit with an error
message without running anything. Syntax errors are like spelling or grammar mistakes in a
language like English.
Runtime errors
If a program is free of syntax errors, it will be run by the Python interpreter. However, the program
may exit if it encounters a runtime error – a problem that went undetected when the program was
parsed, but is only revealed when the code is executed.
• division by zero
• performing an operation on incompatible types
• using an identifier which has not been defined
• accessing a list element, dictionary value or object attribute which doesn’t exist
• trying to access a file which doesn’t exist
The try block lets you test a block of code for errors.
The else block lets you execute code when there is no error.
The finally block lets you execute code, regardless of the result of the try- and except blocks.
try
When an error occurs, or exception as we call it, Python will normally stop and generate an error
message.
Example
try:
print(x)
except:
print("An exception occurred")
Since the try block raises an error, the except block will be executed.
Without the try block, the program will crash and raise an error:
Many Exceptions
You can define as many exception blocks as you want, e.g. if you want to execute a special block
of code for a special kind of error:
Example
Print one message if the try block raises a NameError and another for other errors:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Else
You can use the else keyword to define a block of code to be executed if no errors were raised:
Example
In this example, the try block does not generate any error:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Finally
The finally block, if specified, will be executed regardless if the try block raises an error or not.
Example
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
IOError Exception
It is an error 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. It is also raised for operating system-related
errors.
If the given code is written in a try block, it raises an input/output exception, which is handled in
the except block as shown given below
import sys
def whatever():
try:
f = open ( "foo.txt", 'r' )
except IOError, e:
print e
print sys.exc_type
whatever()
Output
[Errno 2] No such file or directory: 'foo.txt'
<type 'exceptions.IOError'>
Python has several functions for creating, reading, updating, and deleting files.
File Handling
The key function for working with files in Python is the open() function.
"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
In addition you can specify if the file should be handled as binary or text mode
Syntax
To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
The open() function returns a file object, which has a read() method for reading the content of the
file:
Example
f = open("demofile.txt", "r")
print(f.read())
You can return one line by using the readline() method:
Example
f = open("demofile.txt", "r")
print(f.readline())
Close Files
It is a good practice to always close the file when you are done with it.
Example
f = open("demofile.txt", "r")
print(f.readline())
f.close()
Data Streams
● In Python, a data stream is a continuous flow of data that is being read or written from a
source or destination, respectively. Data streams can be used to efficiently process large
amounts of data that are too large to fit into memory all at once.
● Python provides several built-in classes and modules for working with data streams,
including:
● open() function: This built-in function is used to open a file and return a file object. The
file object can be used to read from or write to the file.
● sys.stdin, sys.stdout, and sys.stderr: These built-in objects represent the standard input,
output, and error streams, respectively. They are typically used to read input from the
user and to print output or error messages.
● io module: This module provides classes for working with in-memory streams, such as
BytesIO and StringIO.
● socket module: This module provides classes for working with network sockets, which
can be used to read and write data over a network connection.
● To work with data streams in Python, you typically need to perform the following steps:
1. Open the stream: Use the appropriate function or module to open the stream and obtain a
file object or stream object.
2. Read or write data: Use the methods provided by the file object or stream object to read
or write data from or to the stream.
3. Close the stream: When you are finished working with the stream, be sure to close it
using the close() method or by using a with statement.
In Python, there are three main access modes for writing to a file:
1. "w" mode: This mode is used to open a file in write mode, which means that it will create
a new file if the file does not exist or truncate the file if it already exists. The syntax for
opening a file in write mode is as follows:
● Once the file is open in write mode, you can write to it using the write() method. For
example:
file.write("Hello, world!")
● After writing to the file, you should close it using the close() method. For example:
file.close()
2. "a" mode: This mode is used to open a file in append mode, which means that it will add
new content to the end of the file if it already exists or create a new file if it does not
exist. The syntax for opening a file in append mode is as follows:
● Once the file is open in append mode, you can write to it using the write() method.
For example:
file.write("Hello, world!")
● After writing to the file, you should close it using the close() method. For example:
file.close()
3. "x" mode: This mode is used to open a file in exclusive creation mode, which means that
it will create a new file and raise an error if the file already exists. The syntax for opening
a file in exclusive creation mode is as follows:
Once the file is open in exclusive creation mode, you can write to it using the write()
method. For example:
file.write("Hello, world!")
After writing to the file, you should close it using the close() method. For example:
file.close()
Note: It's important to always close the file after writing to it to ensure that any changes made to the file
are saved and to free up system resources.
Writing Data to a File: To write data to a file in Python, you can open the file in write mode
using the "w" access mode and then use the write() method to write the data. For example:
file.close()
To read data from a file in Python, you can open the file in read mode using the "r" access mode
and then use the read() method to read the data. For example:
data = file.read()
print(data)
file.close()
There are many additional file methods in Python, including readline(), readlines(), tell(), and
seek(). These methods allow you to read individual lines from a file, read all lines into a list, get
the current file position, and set the file position, respectively.
In Python, you can use pipes to communicate between different processes. A pipe is a
mechanism for interprocess communication that allows one process to send data to another
process. To use pipes as data streams in Python, you can use the subprocess module. For
example:
import subprocess
output = p2.communicate()[0]
print(output.decode())
In this example, the first process runs the "ls -l" command and sends its output to the second
process, which runs the "wc -l" command and counts the number of lines in the output.
Handling IOExceptions:
When working with files in Python, it's important to handle IOExceptions properly to avoid
errors and ensure that your program runs smoothly. To handle IOExceptions, you can use a try-
except block. For example:
try:
data = file.read()
print(data)
file.close()
except IOError:
In this example, the try block attempts to open the "example.txt" file and read its contents. If an
IOError occurs, the except block is executed and an error message is printed.
To work with directories in Python, you can use the os module. This module provides many
functions for working with the file system, including functions for creating, deleting, and listing
directories. For example:
import os
os.mkdir("example_dir")
os.chdir("example_dir")
print(os.getcwd())
os.chdir("..")
os.rmdir("example_dir")
● In this example, the mkdir() function is used to create a new directory called
"example_dir".
● the chdir() function is used to change the current working directory to "example_dir".
● the getcwd() function is used to print the current working directory.
● the chdir() function is used again to change the current working directory back to the
parent directory,
● the rmdir() function is used to delete the "example_dir" directory.
Syntax
Following is the syntax for pipe() method −
os.pipe()