You are on page 1of 3

MODULE – 5 ASSIGNMENT

File Handling & Exception Handling

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

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

f = open(r, “d:\color\flower.txt”)

3)Write a note on the following

A. Purpose of Exception Handling


B. Try block
C. Except block
D. Else block
E. Finally block
F. Bulit-in exceptions

4) Write 2 Custom exceptions

ANSWERS

file_1=open(r"C:\Users\admin\.spyder-py3\try.txt")

print(file_1.read())

Exception handling is the process of responding to unwanted or unexpected events when a computer
program runs. Exception handling deals with these events to avoid the program or system crashing, and
without this process, exceptions would disrupt the normal operation of a program.

The try block lets you test a block of code for errors. The except block lets you handle the error. The else
block lets you execute code when there is no error. The finally block lets you execute code, regardless of
the result of the try- and except blocks.
The except block lets you handle the error. The else block lets you execute code when there is no error.
The finally block lets you execute code, regardless of the result of the try- and except blocks.

An else statement can be combined with an if statement. An else statement contains the block of code
that executes if the conditional expression in the if statement resolves to 0 or a FALSE value. The else
statement is an optional statement and there could be at most only one else statement following if.

It defines a block of code to run when the try... except...else block is final. The finally block will be
executed no matter if the try block raises an error or not. This can be useful to close objects and clean
up resources.

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.

class SalaryNotInRangeError(Exception):

"""Exception raised for errors in the input salary.

Attributes:

salary -- input salary which caused the error

message -- explanation of the error

"""

def __init__(self, salary, message="Salary is not in (5000, 15000) range"):

self.salary = salary

self.message = message

super().__init__(self.message)
salary = int(input("Enter salary amount: "))

if not 5000 < salary < 15000:

raise SalaryNotInRangeError(salary)

class InvalidAgeException(Exception):

"Raised when the input value is less than 18"

pass

# you need to guess this number

number = 18

try:

input_num = int(input("Enter a number: "))

if input_num < number:

raise InvalidAgeException

else:

print("Eligible to Vote")

except InvalidAgeException:

print("Exception occurred: Invalid Age")

You might also like