Files and Exceptions
Files and Exceptions
Exceptions Handling
File handling:
• File handling in Python is a powerful and versatile tool that can be
used to perform a wide range of operations.
• Python too supports file handling and allows users to handle files i.e.,
to read and write files, along with many other file handling options, to
operate on files.
• In Python, file handling is a critical aspect that allows you to work with files on
your computer. The built-in open() function is commonly used for file handling.
Here's a basic overview:
• Opening a File:
• To open a file, you use the open() function. It takes two arguments: the name of
the file and the mode in which you want to open the file. Modes include:
• In Python, there are several built-in Python exceptions that can be raised when an error occurs
during the execution of a program. Here are some of the most common types of exceptions in
Python:
• SyntaxError: This exception is raised when the interpreter encounters a syntax error in the code,
such as a misspelled keyword, a missing colon, or an unbalanced parenthesis.
• TypeError: This exception is raised when an operation or function is applied to an object of the
wrong type, such as adding a string to an integer.
• NameError: This exception is raised when a variable or function name is not found in the current
scope.
• IndexError: This exception is raised when an index is out of range for a list, tuple, or other
sequence types.
• KeyError: This exception is raised when a key is not found in a dictionary.
• ValueError: This exception is raised when a function or method is called with an invalid
argument or input, such as trying to convert a string to an integer when the string does not
represent a valid integer.
• AttributeError: This exception is raised when an attribute or method is not found on an object,
such as trying to access a non-existent attribute of a class instance.
• IOError: This exception is raised when an I/O operation, such as reading or writing a file, fails
due to an input/output error.
• ZeroDivisionError: This exception is raised when an attempt is made to divide a number by zero.
• ImportError: This exception is raised when an import statement fails to find or load a module.
• A syntax error in the code :
• amount = 10000
• if(amount > 2999)
• print("You are eligible to purchase Dsa Self Paced")
• ZeroDivisionError:
marks = 10000
a = marks / 0
print(a)
Try and Except Statement – Catching Exceptions:
Try and except statements are used to catch and handle exceptions in Python. Statements that
can raise exceptions are kept inside the try clause and the statements that handle the exception
are written inside except clause.
• Example: Here we are trying to access the array element whose index is out of bound and
handle the corresponding exception.
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
except:
print ("An error occurred")
• try:
• numerator = 10
• denominator = 0
• result = numerator/denominator
• print(result)
• except:
• print("Error: Denominator cannot be 0.")
• except ZeroDivisionError:
• print("Denominator cannot be 0.")
•
• except IndexError:
• print("Index Out of Bound.")
• except:
• # optional block
• # Handling of exception (if required)
• finally:
• # Some code .....(always executed)
• # try block
• try:
• a = 10
• b=0
• print("Result of Division: " + str(a/b))
• except IndexError:
• print("Index Out of Bound.")
• except(ZeroDivisionError):
• print("Result of Division: ")
•
• finally:
• print("Code execution Wrap up!")
Handling FileNotFoundError Exception:
• ‘FileNotFoundError’ is a checked exception in Python and exception
handling should be done by making use of ‘try’ and ‘except’ block.
• Example: Here we have used try and except block to handle the error.
• try:
• file1 = open("Myfolder/abc.txt")
• except:
• print("file not found")
Exception handling with try, except, else, and finally
• divide(3, 2)
• divide(3, 0)