ExceptionAndFileHandling
ExceptionAndFileHandling
Exception Handling
❑ An exception is an error that occurs while a program is running. When an error
happens, Python stops the program unless the error is handled. Exception
handling allows us to manage these errors so our program doesn’t crash and can
continue running or handle the error gracefully.
❑ Python has many built-in exceptions that are raised when your program
encounters an error (something in the program goes wrong).
❑
When these exceptions occur, the Python interpreter stops the current process
and passes it to the calling process until it is handled. If not handled, the program
will crash.
❑ Syntax:
try:
#statements which could generate exception
except:
#Soloution of generated exception
Handling Exception
3
Multiple Exception
You can handle different types of exceptions with multiple except blocks.
python
try:
number = int(input("Enter a number: "))
result = 10 / number
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Please enter a valid number.")
Finally Clause
❑ The finally code block is also a part of exception handling.
When we handle exception using the try and except block, we
can include a finally block at the end.
❑ The finally block is always executed, so it is generally used
for doing the concluding tasks like closing file resources or
closing database connection or may be ending the program
execution with a delightful message.
Syntax:
try:
#statements which could generate exception
except:
#solution of generated exception
finally:
#block of code which is going to execute in any situation
using else and finally
•else: Runs if there were no exceptions.
•finally: Runs no matter what, even if there’s an exception.
try:
number = int(input("Enter a number: "))
result = 10 / number
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Please enter a valid number.")
else:
print("The result is:", result)
finally:
print("This will always run.")
Exception Handling
7
ArithmeticError
•This is a base class for errors related to arithmetic operations.
•Example: Division by zero, overflow, or issues in numeric operations.
•Common Subclasses:
• ZeroDivisionError: Raised when dividing by zero.
• OverflowError: Raised when a number is too large to be represented.
Example-
try:
result = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
FloatingPointError
•This exception is raised for errors related to floating-point operations.
•It is uncommon and usually requires enabling floating-point error checking with
specific modules, as Python handles most floating-point issues automatically.
Example-
import math
try:
math.exp(1000) # May raise OverflowError in some systems
except OverflowError:
print("Floating point overflow!")
IOError
•Raised when an input/output operation fails, like reading or writing files.
•Common Causes: File not found, permission errors, etc
•Example-
try:
with open('non_existent_file.txt', 'r') as file:
content = file.read()
except IOError:
print("File not found or cannot be opened.")
SyntaxError
•Raised when there is an error in the syntax of the Python code.
•Note: This error occurs during the parsing of code, so it’s usually detected before
the program runs.
Example-
try:
exec("print('Hello') print('World')") # Missing semicolon or newline
except SyntaxError:
print("Syntax error in the code.")
IndentationError
•A specific type of SyntaxError, raised when code indentation is incorrect.
Example-
try:
exec("""
def fun():
print("hello")
fun() # This line has incorrect indentation to trigger IndentationError
""")
except IndentationError:
print("Indentation error in the code.")
except SyntaxError:
print("Syntax error in the code.")
ValueError
•Raised when a function receives an argument of the correct type but inappropriate value.
Example
try:
number = int("hello") # Cannot convert a string to an integer
except ValueError:
print("Invalid value for integer conversion.")
RuntimeError
This is a base class for errors that occur during runtime. It generally acts as a catch-all for
unexpected runtime issues.
Example-
try:
# An example of a recursive function that causes a RuntimeError (recursion limit reached)
def recursive_function():
return recursive_function()
recursive_function()
except RuntimeError:
print("Runtime error: Recursion limit reached.")
IndexError
An IndexError occurs when you try to access an index in a list (or other sequence)
that is out of range. This can happen if you try to access an element at an index that
doesn't exist, such as using an index that is greater than the highest index in the list
or negative indexes that aren't valid.
Example-
try:
my_list = [10, 20, 30]
print(my_list[5]) # This will cause an IndexError because index 5 is out of range
except IndexError:
print("IndexError: List index out of range")
Handling Exception…
13
Handling Exception…
14
Handling Exception…
15
Raising Custom errors
In python, we can raise custom errors by using the
`raise` keyword.
# Step 3: Try to execute the function and catch the custom exception
try:
check_value(-5) # This will raise MyCustomError
except MyCustomError as e:
print(f"Caught an error: {e}") # Handle the error
File
20
Opening a File
filename: name of the file that we want to access
accessmode: read, write, append etc.
buffering: 0 – no buffering
1- line buffering
integer greater than 1- buffering action is performed
with the indicated buffer size
Example:
f=open(“abc.txt”,’r’) # open file in current directory
f=open(“C:/Python33/sample.txt”,’r’)#specifying full path
Opening
FileaOpening
File Modes
22
Modes…
23
Modes…
24
Attributes of file object
26
Example
fo.open(“abc.txt”,”w”)
print(“Name of the file:”,fo.name)
print(“Closed or not :”,fo.closed)
print(“Opening mode :”,fo.mode)
print(“Softspace flag :”,fo.softspace)
File object includes the following methods to read data from the
file.
•read(chars): reads the specified number of characters starting
from the current position.
•readline(): reads the characters starting from the current reading
position up to a newline character.
•readlines(): reads all lines until the end of file and returns a list
object.
Reading Files
name = open("filename“,”mode”,buffering)
◼ opens the given file for reading, and returns a file object
>>> f = open("hours.txt")
>>> f.read()
'123 Susan 12.5 8.1 7.6 3.2\n
456 Brad 4.0 11.6 6.5 2.7 12\n
789 Jenn 8.0 8.0 8.0 8.0 7.5\n'
File reading in Python
File reading in Python
f=open('C:\myfile.txt’)
for line in f:
print(line)
f.close()
Deleting a file
Removing a file
Similarly, for writing data to files, we have to use open() with 'wt' mode
Also, we have to use the write() function to write into a file.
# Write text data to a file
with open('filename.txt' , 'wt') as f:
f.write ('hi there, this is a first line of file.\n’)
f.write ('and another line.\n’)
Output
hi there, this is a first line of file.
and another line.
Writing Files
name = open("filename", "w")
name = open("filename", "a")
◼ opens file for write (deletes previous contents), or
◼ opens file for append (new data goes after previous data)
name = open("filename")
for line in name:
statements
The above statement automatically close the file after the nested
block of code.
The advantage of using with statement is that it is guaranteed to
close the file.
If an exception occurs before the end of the block, it will close the
file before the exception is caught by an outer exception handler
Renaming a file
Renaming a file
f = open('myfile.txt', 'w')
lines = ['line 1', 'line 2', 'line 3']
for line in lines:
f.write(line + '\n')
f.close()
File Position
43
seek() method
The seek() function allows you to move the current position
within a file to a specific point. The position is specified
in bytes, and you can move either forward or backward from
the current position. For example:
with open('file.txt', 'r') as f:
# Move to the 10th byte in the file
f.seek(10)
# Read the next 5 bytes
data = f.read(5)
seek() method
◼ The seek(offset, from) method changes the current file
position.
◼ The offset argument indicates the number of bytes to be
moved.
◼ from: Specifies the reference position:
◼ 0: Start of the file.
◼ 1: Current file pointer position.
◼ 2: End of the file.
f = open('example.txt', 'w+')
f.write("Hello, world!")
f.seek(0) # Move pointer to the beginning of the file
print(f.read()) # Output: "Hello, world!"
f.close()
Example 2: Using seek with from=1 (current position)
f = open('example.txt', 'w+')
f.write("Hello, world!")
f.seek(5, 0) # Move to the 5th byte from the beginning
f.seek(2, 1) # Move 2 bytes forward from the current
position
print(f.read()) # Output: ", world!"
f.close()
seek() method
Example 3: Using seek with from=2 (end of the file)
f = open('example.txt', 'w+')
f.write("Hello, world!")
f.seek(-6, 2) # Move 6 bytes backward from the end
print(f.read()) # Output: "world!"
f.close()
tell() method
The tell() function returns the current position within the
file, in bytes. This can be useful for keeping track of your
location within the file or for seeking to a specific
position relative to the current position. For example:
Output- Hello
Advantages of File Handling
•Versatility : File handling in Python allows you to perform a wide range
of operations, such as creating, reading, writing, appending, renaming,
and deleting files.
•Security risks : File handling in Python can also pose security risks,
especially if the program accepts user input that can be used to access or
modify sensitive files on the system.
17