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

8 - File Exception Handling

Uploaded by

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

8 - File Exception Handling

Uploaded by

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

Presented To:

Ma’am Maryam Wajeeha

Presented By:
2023/R2022-IM-27
2022/R2021-IM-30
23-IM-42
File & Exception
Handling

1
Index
1. File Handling
i. How to Create a Text File
ii. How to Append Data to a File
iii. How to Read a File
iv. File Modes in Python

2. Exception Handling
i. What is an Exception in Python?
ii. Common Examples of Exception
iii. Rules of Exceptions
iv. Exceptional Handling Mechanism
• The Try Statement
• The catch Statement
• The Raise Statement 2
1. File Handling
i. How to Create a Text File

With Python you can create a .text files (gktcs.txt) by using the
below code.

Step 1:

f= open(“gktcs.txt","w+")

4
 We declared the variable f to open a file named gktcs.txt.
Open takes 2 arguments, the file that we want to open and a
string that represents the kinds of permission or operation
we want to do on the file
 Here, we used "w" letter in our argument, which indicates
write and will create a file if it does not exist in library
 Plus sign indicates both read and write.
 The available option beside "w" are, "r" for read, and "a" for
append

5
Step 2:

for i in range(10):
f.write("This is line %d\r\n" % (i+1))

6
 We have a for loop that runs over a range of 10 numbers.
 Using the write function to enter data into the file.
 The output we want to iterate in the file is "this is line
number", which we declare with write function and then
percent d (displays integer)
 So basically we are putting in the line number that we are
writing, then putting it in a carriage return and a new
line character

7
Step 3:

f.close()

This will close the instance of the file gktcs.txt stored

8
ii. How to Append Data to a File
Step 1:

f=open(“gktcs.txt", "a+")

Once again if you could see a plus sign in the code, it indicates
that it will create a new file if it does not exist. But in our case
we already have the file, so we are not required to create a new
file.

9
Step 2:

for i in range(2):
f.write("Appended line %d\r\n" % (i+1))

This will write data into the file in append mode.

10
iii. How to Read a File

Step 1:
Open the file in Read mode

f=open(“gktcs.txt", "r")

11
Step 2:

We use the mode function in the code to check that the file is in
open mode. If yes, we proceed ahead

if f.mode == 'r':

12
Step 3:
Use f.read to read file data and store it in variable content

contents =f.read()

13
iv. File Modes in Python

Mode Description
'r' This is the default mode. It Opens file
for reading.

'w' This Mode Opens file for writing.


If file does not exist, it creates a new
file.
If file exists it truncates the file.
'x' Creates a new file. If file already exists,
the operation fails.

14
'a' Open file in append mode.
If file does not exist, it creates a new
file.
't' This is the default mode. It opens in
text mode.

'b' This opens in binary mode.

'+' This will open a file for reading and


writing (updating)

15
2. Exception Handling

i. What is an Exception in Python?

An exception is an error which happens at the time of


execution of a program. However, while running a program,
Python generates an exception that should be handled to
avoid your program to crash. In Python language, exceptions
trigger automatically on errors, or they can be triggered and
intercepted by your code.

16
ii. Common Examples of Exception

 Division by Zero
 Accessing a file which does not exist.
 Addition of two incompatible types
 Trying to access a nonexistent index of a sequence
 Removing the table from the disconnected database server.
 ATM withdrawal of more than the available amount

17
iii. Rules of Exceptions

 Exceptions must be class objects


 Forclass exceptions, you can use try statement with
an except clause which mentions a particular class.
 Even if a statement or expression is syntactically correct, it
may display an error when an attempt is made to execute
it.
 Errors found during execution are called exceptions,
and they are not unconditionally fatal.

18
 Exceptions must be class objects
 Forclass exceptions, you can use try statement with
an except clause which mentions a particular class.
 Even if a statement or expression is syntactically correct, it
may display an error when an attempt is made to execute it.
 Errors found during execution are called exceptions,
and they are not unconditionally fatal.

19
 Exceptions must be class objects
 Forclass exceptions, you can use try statement with
an except clause which mentions a particular class.
 Even if a statement or expression is syntactically correct, it
may display an error when an attempt is made to execute
it.
 Errors found during execution are called exceptions,
and
they are not unconditionally fatal.

20
iv. Exceptional Handling Mechanism
Exception handling is managed by the following 4 keywords:

1. try
2. catch
3. finally
4. throw

21
The Try Statement:

A try statement includes keyword try, followed by a colon (:)


and a suite of code in which exceptions may occur. It has one or
more clauses.

During the execution of the try statement, if no exceptions


occurred then, the interpreter ignores the exception handlers
for that specific try statement.

22
In case, if any exception occurs in a try suite, the try suite
expires and program control transfers to the matching except
handler following the try suite.

Syntax:

try:
statement(s)

23
The catch Statement:

Catch blocks take one argument at a time, which is the type of


exception that it is likely to catch. These arguments may range
from a specific type of exception which can be varied to a
catch-all category of exceptions.

24
Example:

try
}
catch (ArrayIndexOutOfBoundsException e)
{ System.err.printin("Caught first " +
e.getMessage());
}
catch (IOException e)
{ System.err.printin("Caught second
" + e.getMessage());
}

25
Finally Block:

Finally block always executes irrespective of an exception


being thrown or not. The final keyword allows you to create a
block of code that follows a try-catch block.

Finally, clause is optional. It is intended to define clean-up


actions which should be that executed in all conditions.

26
try:
raise KeyboardInterrupt
finally:
print 'welcome, world!'
Output
Welcome,
world!
KeyboardInterrupt

27
The Raise Statement:

The raise statement specifies an argument which initializes the


exception object. Here, a comma follows the exception name,
and argument or tuple of the argument that follows the comma.

28
Syntax:

raise [Exception [, args [, traceback]]]

In this syntax, the argument is optional, and at the time


of execution, the exception argument value is always none.

29
Thank You For
Your
Attention

You might also like