0% found this document useful (0 votes)
23 views

UNIT-4 Exception -f File Handling

This document covers errors and exception handling in Python, detailing compile-time errors, logical errors, and runtime errors, along with their examples. It explains exception handling mechanisms using try, except, else, and finally blocks, as well as creating and raising custom exceptions. Additionally, it discusses file handling, including types of files, opening and closing files, and reading file content.

Uploaded by

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

UNIT-4 Exception -f File Handling

This document covers errors and exception handling in Python, detailing compile-time errors, logical errors, and runtime errors, along with their examples. It explains exception handling mechanisms using try, except, else, and finally blocks, as well as creating and raising custom exceptions. Additionally, it discusses file handling, including types of files, opening and closing files, and reading file content.

Uploaded by

abithhussain033
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

UNIT-4

4.Errors and Exception handling


Introduction to errors:
● Sometimes while executing a Python program, the program does not execute at all or the program executes but
generates unexpected output or behaves abnormally.
● These occur when there are syntax errors, runtime errors or logical errors in the code. In Python, exceptions are
errors that get triggered automatically.
● However, exceptions can be forcefully triggered and handled through program code. In this chapter, we will learn
about exception handling in Python programs.
1.Compile time errors(Syntax errors):
Syntax Errors:
These occur when you make a mistake in the syntax of your code. It could be a typo, a missing parenthesis, or a similar
issue.
Example-1:

i 5 > 2:
print("Five is greater than two!")
Output:
Cell In[2], line 1
i 5 > 2:
^
SyntaxError: invalid syntax

Example-2:
if 5 > 2:
print("Five is greater than two!")
Output:
Cell In[3], line 2
print("Five is greater than two!")
^
IndentationError: expected an indented block after 'if' statement on line 1
2.Logical errors:
● These errors do not cause the program to crash, but they lead to incorrect results. They are often the most
challenging to debug because the code runs without any error messages.
Example:

def add(a,b):
result=a-b
return result
add(2,3)
Output:
-1
In this case, the function is intended to add two numbers, but due to a logical error (subtracting instead of adding), it
will not produce the correct result.

3. Runtime Errors (Exceptions):


● These occur during the execution of the program when something unexpected happens, and the program cannot
continue.
● Examples include division by zero and accessing an index that doesn't exist in a list, or attempting to open a file that
doesn't exist. Example-1:
x = 10 / 0
This will raise a ZeroDivisionError since division by zero is not allowed. Example-2:

a=10
b=input("enter b:")
c=a//b
print(c)
Output:
enter b:2
--------------------------------------------------------------------- ------
TypeError Traceback (most recent call last)
Cell In[6], line 3
1 a=10
2 b=input("enter b:")
----> 3 c=a//b
4 print(c)

TypeError: unsupported operand type(s) for //: 'int' and 'str'

Common exception
. NoName of the Built-in
ExceptionExplanation
1. SyntaxError It is raised when there is an error in the syntax of the Python code.

2. ValueError It is raised when a built-in method or operation receives an argument that


has the right data type but mismatched or inappropriate values.

3. IOError It is raised when the file specified in a program statement cannot beopened.

4 KeyboardInterrupt It is raised when the user accidentally hits the Delete or Esc key while
executing a program due to which the normal flow of the program is
interrupted.

5 ImportError It is raised when the requested module definition is not found.

6 EOFError It is raised when the end of file condition is reached without readingany
data by input().

7 ZeroDivisionError It is raised when the denominator in a division operation is zero.

8 IndexError It is raised when the index or subscript in a sequence is out of range.

9 NameError It is raised when a local or global variable name is not defined.

10 IndentationError It is raised due to incorrect indentation in the program code.

11 TypeError It is raised when an operator is supplied with a value of incorrectdata type.

12 OverFlowError It is raised when the result of a calculation exceeds the maximumlimit for
numeric data type.
Exception Handling:
A runtime error, also known as an exception, occurs during the execution of a
program when something unexpected or erroneous happens. Exception
handling is a mechanism in programming languages, including Python, that
allows developers to manage and respond to these runtime errors in a
controlled manner. Handling exceptions helps prevent a program from crashing and allows for graceful error recovery.

In Python, the try, except, else, and finally blocks are used for exception handling:

Exception handling is the way to handle the Exception so that the other part of the code can be executed without any
disruption.
1.TryBlock:

The try block encloses the code that might raise an exception. If an exception
occurs within this block, it is caught by the corresponding except block.

Example 1

try:
# Code that might raise a runtime error
result = 10 / 0 # Example: Division by zero
except ZeroDivisionError:
# Code to handle the specific exception
print("Cannot divide by zero!")

2. Multiple Except Blocks:

You can have multiple except blocks to handle different types of exceptions.

Example :
try:
value = int(input("Enter a number: "))
result = 10 / value
except ValueError:
print("Invalid input! Please enter a valid number.")
except ZeroDivisionError:
print("Cannot divide by zero!")

3. Generic Exception Handling:


You can use a generic except block to catch any exception, but it's generally
recommended to catch specific exceptions whenever possible.

Example:
try:
# Code that might raise a runtime error
result = 10 / 0 # Example: Division by zero
except Exception as e:
# Code to handle the exception
print(f"An error occurred: {e}")

4. Else Block:

The else block is executed if no exception occurs in the try block. Example:

try:
value = int(input("Enter a number: "))
result = 10 / value
except ValueError:
print("Invalid input! Please enter a valid number.")
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print(f"The result is: {result}")

5. Finally Block:

● The finally block is executed regardless of whether an exception occurs or not. It's often used for cleanup
operations.

Example:
try:
file = open("example.txt", "r")
# Code that might raise an exception while reading the file except FileNotFoundError:
print("File not found!")
finally:
# Code that will be executed no matter what
file.close()

Creating and Raising Custom Exceptions:


● You can create your own custom exceptions by defining a new class that
inherits from the built-in Exception class or one of its subclasses. ●
Creating custom exceptions in Python allows you to define your own
exception classes tailored to specific situations in your code. This can
enhance the clarity of your error handling and make it easier to manage different error cases.

Example:class

AgeError(Exception):

pass

class TooYoungError(AgeError):
pass

class TooOldError(AgeError):

pass

while True:
try:

age = int(input("Enter your age: "))

if age < 18:

raise TooYoungError
elif age > 100:

raise TooOldError

else:

break

except ValueError:
print("Invalid input. Please enter a valid integer for age.")

except TooYoungError:

print("Sorry, you are too young to use this service. Please try again.") except TooOldError:

print("Sorry, you are too old to use this service. Please try again.")

print(f"Congratulations! You are eligible. Your age is {age}.")

Raising Built-in Exceptions:

● In Python, the raise statement is used to raise an exception explicitly. This allows you to signal that a particular
condition or situation has occurred, and the corresponding exception should be handled by the appropriate except block.
Here's a brief explanation and an example:
raise Statement:

The raise statement is used to raise an exception manually. It generally follows the
format:

raise ExceptionType("Optional custom message")

● ExceptionType: The type of exception to be raised. It can be a built-in


exception type (e.g., ValueError, TypeError) or a custom exception type. ● "Optional custom
message": An optional custom message that provides additional information about the reason for raising the exception.

Example Code:

try:
number = int(input("Enter a number: "))
if number % 2 == 0:
print("The number is even.")
else:
raise ValueError("The number is odd.")
except ValueError as ve:
print(f"Invalid input: {ve}")
File Handling in Python
Files
• Files are named locations on disk to store related information.
They are used to permanently store data in a non-volatile
memory (e.g. hard disk).
• Since Random Access Memory (RAM) is volatile (which loses its
data when the computer is turned off), we use files for future
use of the data by permanently storing them.
• When we want to read from or write to a file, we need to open
it first. When we are done, it needs to be closed so that the
resources that are tied with the file are freed.
• Hence, in Python, a file operation takes place in the following
order:
– Open a file
– Read or write (perform operation)
– Close the file

Text Files and Binary Files


Types Of File in Python
• There are two types of files in Python and
each of them are explained below in detail
with examples for your easy understanding.
They are:

• Binary file
• Text file
Binary files in Python
• All binary files follow a specific format. We can
open some binary files in the normal text editor
but we can’t read the content present inside the
file. That’s because all the binary files will be
encoded in the binary format, which can be
understood only by a computer or machine.
• For handling such binary files we need a specific
type of software to open it.
• For Example, You need Microsoft word software
to open .doc binary files. Likewise, you need a pdf
reader software to open .pdf binary files and you
need a photo editor software to read the image
files and so on.
Binary files in Python (cont…1)
• Most of the files that we see in our computer
system are called binary files.
• Example:
• Document files: .pdf, .doc, .xls etc. • Image
files: .png, .jpg, .gif, .bmp etc. • Video files:
.mp4, .3gp, .mkv, .avi etc. • Audio files: .mp3,
.wav, .mka, .aac etc. • Database files: .mdb,
.accde, .frm, .sqlite etc. • Archive files: .zip,
.rar, .iso, .7z etc. • Executable files: .exe, .dll,
.class etc.
Text files in Python
• A text file is usually considered as sequence of
lines. Line is a sequence of characters (ASCII),
stored on permanent storage media. Although
default character coding in python is ASCII but
supports Unicode as well.
• in text file, each line is terminated by a special
character, known as End of Line (EOL). From
strings we know that \n is newline character.
• at the lowest level, text file is collection of bytes.
Text files are stored in human readable form. • they
can also be created using any text editor.
Text files in Python (Cont…1)
• Text files don’t have any specific encoding and
it can be opened in normal text editor itself. •
Example:
• Web standards: html, XML, CSS, JSON etc.
• Source code: c, app, js, py, java etc. •
Documents: txt, tex, RTF etc.
• Tabular data: csv, tsv etc.
• Configuration: ini, cfg, reg etc.
Opening or Creating a New File in Python
• The method open() is used to open an existing file or
creating a new file. If the complete directory is not given
then the file will be created in the directory in which the
python file is stored. The syntax for using open()
method is given below.
– Syntax:
– file_object = open( file_name, “Access Mode”, Buffering ) •
The open method returns file object which can be stored
in the name file_object (file-handle).
• File name is a unique name in a directory. The open()
function will create the file with the specified name if it
is not already exists otherwise it will open the already
existing file.
Opening Files in Python
(cont…1) • The access mode
it is the string which tells in what mode the file should
be opened for operations. There are three different
access modes are available in python.
• Reading: Reading mode is crated only for reading the
file. The pointer will be at the beginning of the file. •
Writing: Writing mode is used for overwriting the
information on existing file.
• Append: Append mode is same as the writing mode.
Instead of over writing the information this mode
append the information at the end.
• Below is the list of representation of various access
modes in python.
Opening Files in Python
(cont…2) Access modes in Text Files
• ‘r' – Read Mode: Read mode is used only to read data
from the file.
• ‘w' – Write Mode: This mode is used when you want to
write data into the file or modify it. Remember write
mode overwrites the data present in the file.
• ‘a' – Append Mode: Append mode is used to append
data to the file. Remember data will be appended at
the end of the file pointer.
• ‘r+' – Read or Write Mode: This mode is used when we
want to write or read the data from the same file. • ‘a+' –
Append or Read Mode: This mode is used when we want
to read data from the file or append the data into the
same file.
Opening Files in Python
(cont…3) Access modes in Binary Files
• ‘wb’ – Open a file for write only mode in the
binary format.
• ‘rb’ – Open a file for the read-only mode in the
binary format.
• ‘ab’ – Open a file for appending only mode in the
binary format.
• ‘rb+’ – Open a file for read and write only mode
in the binary format.
• ‘ab+’ – Open a file for appending and read-only
mode in the binary format.
Opening Files in Python
(cont…4) What is Buffering ?
• Buffering is the process of storing a chunk of a
file in a temporary memory until the file loads
completely. In python there are different
values can be given. If the buffering is set to 0
, then the buffering is off. The buffering will be
set to 1 when we need to buffer the file.
Opening Files in Python
(cont…5) Examples Opening a file:
# open file in current directory
• f = open("test.txt“, “r”)

# specifying full path


• f = open(r“D:\temp\data.txt“, “r”)
– –raw string
• f = open(“D:\\temp\\data.txt“, “r”)
– -absolute path
Closing Files in Python
• After processing the content in a file, the file must
be saved and closed. To do this we can use
another method close() for closing the file. This is
an important method to be remembered while
handling files in python.
• Syntax: file_object.close()

string = "This is a String in Python"


my_file =
open(my_file_name.txt,"w+",1)
my_file.write(string)
my_file.close()
print(my_file.closed)
Reading Information in the File • In
order to read a file in python, we must open the
file in read mode.
• There are three ways in which we can read the
files in python.
– read([n])
– readline([n])
– readlines() – all lines returned to a list
• Here, n is the number of bytes to be read.

Reading Information in the File (cont…1)


Example 1:
my_file = open(“C:/Documents/Python/test.txt”,
“r”) print(my_file.read(5))
Output:
Hello

•Here we are opening the file test.txt in a read-only


mode and are reading only the first 5 characters of
the file using the my_file.read(5) method.

Reading Information in the File (cont…2)


Example 2:
my_file = open(“C:/Documents/Python/test.txt”,
“r”) print(my_file.read())
Output:
Hello World
Hello Python
Good Morning
Here we have not provided any argument inside
the read() function. Hence it will read all the
content present inside the file.

Reading Information in the File (cont…3)


Example 3:
my_file = open(“C:/Documents/Python/test.txt”,
“r”) print(my_file.readline(2))
Output:
He

This function returns the first 2 characters of the


next line.

Reading Information in the File (cont…4)


Example 4:
my_file = open(“C:/Documents/Python/test.txt”,
“r”) print(my_file.readline())

Output:
Hello World

Using this function we can read the content of


the file on a line by line basis.

Reading Information in the File (cont…5)


Example 5:
my_file = open(“C:/Documents/Python/test.txt”,
“r”) print(my_file.readlines())

Output:
*‘Hello World\n’, ‘Hello Python\n’, ‘Good Morning’+
Here we are reading all the lines present inside
the text file including the newline characters.
Reading Information in the File (cont…6)

Reading a specific line from a File


line_number = 4
fo = open(“C:/Documents/Python/test.txt”,
’r’) currentline = 1
for line in fo:
if(currentline == line_number):
print(line)
break
currentline = currentline +1
Output:
How are You
In the above example, we are trying to read only the
4th line from the ‘test.txt’ file using a “for loop”.
Reading Information in the File (cont…7)

Reading the entire file at once


filename =
“C:/Documents/Python/test.txt” filehandle
= open(filename, ‘r’)
filedata = filehandle.read()
print(filedata)

Output:
Hello World
Hello Python
Good Morning
How are You
Write to a Python File
• In order to write data into a file, we must open the file in
write mode.
• We need to be very careful while writing data into the file
as it overwrites the content present inside the file that you
are writing, and all the previous data will be erased.
• We have two methods for writing data into a file as shown
below.

– write(string)
– writelines(list)
• Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.write(“Hello World”)
The above code writes the String ‘Hello World’ into the ‘test.txt’
file.
Write to a Python File (cont…1)
Example 2:
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.write(“Hello World\n”)
my_file.write(“Hello Python”)

•The first line will be ‘Hello World’ and as we have mentioned \n character, the
cursor will move to the next line of the file and then write ‘Hello Python’.
•Remember if we don’t mention \n character, then the data will be written
continuously in the text file like ‘Hello WorldHelloPython’
Example 3:
fruits = *“Apple\n”, “Orange\n”, “Grapes\n”, “Watermelon”+
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.writelines(fruits)

The above code writes a list of data into the ‘test.txt’ file simultaneously.

Append in a Python
File
To append data into a file we must open the file in
‘a+’ mode so that we will have access to both
the append as well as write modes.

Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.write (“Strawberry”)
The above code appends the string ‘Strawberry’ at the end of the ‘test.txt’ file

Example 2:
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.write (“\nGuava”)

The above code appends the string ‘Apple’ at the end


of
the ‘test.txt’ file in a new line.

You might also like