Module 5 File - Exception Handling

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

#1)Write the code in python to open a file named “try.

txt”

# Using open() function


file_path = "try.txt"

# Open the file in write mode


with open(file_path, 'w') as file:
# Write content to the file
file.write("Hello, this is a new text file created using open() function.")

print(f"File '{file_path}' created successfully.")

file.close()

#2)What is the purpose of ‘r’ as a prefix in the given statement?


f = open(r, "C:\Users\Admin\try.txt") # r is used to read the file
# 3)Write a note on the following

# A. Purpose of Exception Handling


# Reply : Exception handling in Python is a process of resolving errors that occur
in a program.
# This involves catching exceptions, understanding what caused them, and
then responding accordingly.
# Exceptions are errors that occur at runtime when the program is being
executed.
# They are usually caused by invalid user input or code that is invalid in
Python.
# Exception handling allows the program to continue to execute even if an
error occurs.
# Few of them are as below :
# NameError: This Exception is raised when a name is not found in the
local or global namespace.
# IndexError: This Exception is raised when an invalid index is used to
access a sequence.
# KeyError: This Exception is thrown when the key is not found in the
dictionary.
# ValueError: This Exception is thrown when a built-in operation or
function receives an argument of the correct type and incorrect value.
# IOError: This Exception is raised when an input/output operation fails,
such as when an attempt is made to open a non-existent file.
# ImportError: This Exception is thrown when an import statement cannot
find a module definition or a from ... import statement cannot find a name to
import.
# SyntaxError: This Exception is raised when the input code does not
conform to the Python syntax rules.
# TypeError: This Exception is thrown when an operation or function is
applied to an object of inappropriate type
# AttributeError: occurs when an object does not have an attribute being
referenced, such as calling a method that does not exist on an object.
# ArithmeticError: A built-in exception in Python is raised when an
arithmetic operation fails. This Exception is a base class for other specific
arithmetic exceptions, such as ZeroDivisionError and OverflowError.
# Floating point error: It is a type of arithmetic error that can occur in
Python and other programming languages that use floating point arithmetic to
represent real numbers.
# ZeroDivisionError: This occurs when dividing a number by zero, an
invalid mathematics operation.
# FileExistsError: This is Python's built-in Exception thrown when
creating a file or directory already in the file system.
# PermissionError: A built-in exception in Python is raised when an
operation cannot be completed due to a lack of permission or access rights.

# B. Try block
# Reply : In Python, the try block is used to enclose code that might raise an
exception.
# If an exception is raised within the try block, the code in the
corresponding except block is executed.

# C. Except block
# Reply : Python provides a way to catch specific exceptions during a program's
execution.
# This is done with the "try" statement

# D. Else block
# Reply : The code inside the try block is executed until an exception is raised.
# If an exception is raised, the code inside the except block is executed.
# The code inside the else block is executed if no exception is raised.

# E. Finally block
# Reply : Finally and Else are two keywords used in try..except blocks in Python.
# The Finally block executes a set of statements, regardless of the result
of the try..except blocks.
# This is useful when you want to clean up resources like closing a file or
connection, irrespective of whether an exception occurred or not.
# The Else block is used to execute a set of statements only if the try
block does not raise an exception.
# It is useful for code that must be executed if the try block does not
raise an exception.

# F. Built-in exceptions
# Reply : Python Built-in Exceptions. Python has a number of built-in exceptions,
# such as the well-known errors SyntaxError, NameError, and TypeError.
# These Python Exceptions are thrown by standard library routines or by the
interpreter itself.
# They are built-in, which implies they are present in the source code at
all times.

# 4) Write 2 Custom exceptions

# 1st Custom exception [Class]

class MyCustomError(Exception):

def __init__(self, message):


self.message = message
super().__init__(self.message)

# 2nd Custom exception [Class]

def divide(a, b):


if b == 0:
raise MyCustomError("Division by zero is not allowed", 400)
return a / b

You might also like