You are on page 1of 10

1

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:

1. Syntax errors 2. Runtime errors and 3. Logical errors

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.

Some examples of Python Runtime errors −

• 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

Python Try Except

The try block lets you test a block of code for errors.

The except block lets you handle the error.

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.

III – B.Sc IT – B --SKACAS PYTHON PROGRAMMING


2

try

When an error occurs, or exception as we call it, Python will normally stop and generate an error
message.

These exceptions can be handled using the try statement:

Example

The try block will generate an exception, because x is not defined:

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")

III – B.Sc IT – B --SKACAS PYTHON PROGRAMMING


3

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

III – B.Sc IT – B --SKACAS PYTHON PROGRAMMING


4

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'>

File Handling in Python

File handling is an important part of any web application.

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.

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

In addition you can specify if the file should be handled as binary or text mode

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)

III – B.Sc IT – B --SKACAS PYTHON PROGRAMMING


5

Syntax

To open a file for reading it is enough to specify the name of the file:

f = open("demofile.txt")

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("demofile.txt", "r")
print(f.read())
You can return one line by using the readline() method:

Example

Read one line of the file:

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

Close the file when you are finish with it:

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:

III – B.Sc IT – B --SKACAS PYTHON PROGRAMMING


6

● 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.

with open('example.txt', 'r') as f:


for line in f:
print(line)
● In this example, we use the open() function to open a file called 'example.txt' in read
mode ('r'). We then use a for loop to read each line from the file and print it to the
console. Finally, we use a with statement to ensure that the file is automatically closed
when we are finished reading from it.

Access Modes Writing

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:

file = open("filename.txt", "w")

● 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:

III – B.Sc IT – B --SKACAS PYTHON PROGRAMMING


7

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:

file = open("filename.txt", "a")

● 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:

file = open("filename.txt", "x")

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 = open("example.txt", "w")

file.write("This is some text that will be written to the file.")

file.close()

Reading Data from a File:

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:

file = open("example.txt", "r")

III – B.Sc IT – B --SKACAS PYTHON PROGRAMMING


8

data = file.read()

print(data)

file.close()

Additional File Methods:

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.

Using Pipes as Data Streams:

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

p1 = subprocess.Popen(["ls", "-l"], stdout=subprocess.PIPE)

p2 = subprocess.Popen(["wc", "-l"], stdin=p1.stdout, stdout=subprocess.PIPE)

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:

file = open("example.txt", "r")

data = file.read()

print(data)

III – B.Sc IT – B --SKACAS PYTHON PROGRAMMING


9

file.close()

except IOError:

print("An error occurred while reading the file.")

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.

Working with Directories:

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.

III – B.Sc IT – B --SKACAS PYTHON PROGRAMMING


10

Using Pipes as Data Streams


Pipe is a Python library that enables you to use pipes in Python. A
pipe (|) passes the results of one method to another method.
Python method pipe() creates a pipe and returns a pair of file descriptors (r, w) usable for reading
and writing, respectively

Syntax
Following is the syntax for pipe() method −
os.pipe()

III – B.Sc IT – B --SKACAS PYTHON PROGRAMMING

You might also like