0% found this document useful (0 votes)
13 views3 pages

Python Exception and File Handling Guide

The document covers exception handling in Python, detailing types of errors, the difference between raise and assert, and common built-in exceptions. It also explains try-except structures for managing exceptions and introduces file handling concepts, including differences between text and binary files, file functions, and access modes. Key definitions related to exceptions and file operations are provided to enhance understanding.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views3 pages

Python Exception and File Handling Guide

The document covers exception handling in Python, detailing types of errors, the difference between raise and assert, and common built-in exceptions. It also explains try-except structures for managing exceptions and introduces file handling concepts, including differences between text and binary files, file functions, and access modes. Key definitions related to exceptions and file operations are provided to enhance understanding.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 1 – Exception Handling

1. Types of Errors

Type Description Example


Syntax Error Occurs when Python syntax rules are broken. print "Hello"
Runtime Error Occurs during program execution. 10/0
Logical Error Program runs but gives wrong output. (a+b)/3 instead of (a+b)/2

2. Difference between raise and assert

Feature raise assert


Purpose Manually raise an exception Test a condition during runtime
When used To trigger an exception on purpose To check correctness of a condition
Syntax raise ExceptionType('message') assert condition, 'message'
Example raise ValueError('Invalid value') assert x>0, 'x must be positive'

3. Five Common Built-in Exceptions

Exception Meaning Example


ZeroDivisionError Division by zero 10/0
ValueError Invalid type of value int('abc')
TypeError Invalid type of operand '2' + 2
IndexError Invalid list index a=[1,2]; a[3]
KeyError Accessing invalid key d={'a':1}; d['b']

4. Key Definitions

Exception Object: Object created when an error occurs.

Exception Handling: Detecting and managing runtime errors.

Throwing an Exception: Creating and raising an exception object using raise.

Catching an Exception: Handling exception using try–except.

Run-time System: Python environment that detects exceptions.

Exception Handler: Code block that deals with exceptions.

5. try–except Structures
try … except: Used to handle exceptions.

Example:
try:
a=10/0
except ZeroDivisionError:
print('Cannot divide by zero!')

try … except … else: else block runs if no exception occurs.

Example:
try:
x=int(input('Enter number: '))
except ValueError:
print('Invalid input!')
else:
print('Valid number.')

try … except … else … finally: finally block always executes.

Example:
try:
f=open('[Link]')
except FileNotFoundError:
print('File not found')
else:
print('File read success')
finally:
[Link]()

Chapter 2 – File Handling in Python

1. Difference between Text File and Binary File

Feature Text File Binary File


Content Human-readable text Binary (0s and 1s)
Example .txt, .csv .dat, .bin
Usage open('[Link]','r') open('[Link]','rb')

2. File Functions – Purpose, Syntax, Example

Function Purpose Syntax/Example


open() Opens a file f=open('[Link]','r')
close() Closes a file [Link]()
open() with clause Auto-closes file with open('[Link]','r') as f:

3. Important Differences
Functions Difference
write() vs writelines() write() writes one string; writelines() writes list of strings
read(n) vs read() read(n) reads n chars; read() reads entire file
readline(n) vs readlines() readline() reads one line; readlines() reads all lines
seek() vs tell() seek() moves cursor; tell() gives cursor position
dump() vs load() dump() saves object; load() retrieves object
Serialization vs Deserialization Convert object→file vs file→object

4. Definitions

File: Collection of data stored permanently.

File Offset: Current position of file cursor.

Reference Point: Starting position for seek().

Pickling: Converting object to byte stream.

Unpickling: Restoring object from byte stream.

5. File Access Modes

Mode Meaning Description


r Read Opens file for reading
w Write Opens file for writing (overwrites)
a Append Opens file to add data at end
r+ Read/Write Read and write both allowed
w+ Write/Read Overwrites and allows reading
a+ Append/Read Appends and allows reading
rb / wb / ab Binary modes Same but for binary files

You might also like