OOP-PPT-Module 5 Part 2
OOP-PPT-Module 5 Part 2
Error :Typically refers to a mistake or issue in the code that prevents it from running as intended.
Exception : It is an event that occurs during the execution of a program that disrupts the normal flow of
instructions
Basically ,there are (at least) two kinds of errors and exception
⮚ Syntax Error
⮚ Exceptions
⮚ Syntax Errors
⮚ Logical Errors
Synchronous Exception : While synchronous exception(like divide by zero ,array index out of bound can be
controlled by the program
Asynchronous Exception : Asynchronous Exceptions (like an interrupt from keyboard, hardware malfunction or
disk failure) are caused by events that are beyond the control of the program
if a< b :
print(“a is bigger than b”)
Detection
In compiled languages, the compiler indicates the syntax The programmers have to detect the error by themself
error with the location and what the error is
Simplicity
It is easier to identify a syntax error. It is comparatively difficult to identify a logical error.
>> 5/0
ZeroDivisionError: division by zero
>> var + 10
NameError: name 'var' is not defined
1. You are developing a program that simulates a simple game where players can roll a six-sided
die. However, the player accidentally enters a value that is not an integer when trying to roll the
die.
2. You are developing a Python program that processes a list of student grades. However, there is
a typo in one of the variable names used to store the grade value, leading to a NameError.
3. You are developing a Python program that calculates the average of a list of numbers. However,
there is a scenario where the list is empty, leading to a ZeroDivisionError.
1. What type of error is raised when attempting to access a variable that has not been defined?
a) SyntaxError b) ValueError c) NameError d) TypeError
2. Which of the following is an example of a syntax error in Python?
a) Forgetting to import a module needed for the program. b)Dividing a number by zero.
c) Misspelling a variable name in the code. d)Using an incorrect conditional statement.
3. Which of the following is an example of a logical error?
a) Using a reserved keyword as a variable name b) Trying to access a file that does not exist
c) A program that calculates the average of a list of numbers but gives the sum of all numbers
a)Hello, world! b)SyntaxError: EOL while scanning string literal c) SyntaxError: invalid syntax d) None
2 . What will be the output of the code snippet? 3. Identify the type of error in the following code?
result = 10 * 2 / 5 + 3 Print(“Good Morning”)
print(result) print(“Good night)
a)7.0 b) 5.0 c) 8.0 a) Name error, Syntax Error b) Semantic, Syntax
d) Indentation error: unexpected indent c) Semantic, Semantic d) Syntax, Semantic
Syntax:
try:
statements
. except ExceptionName:
statements
Step 2b: If an exception occurs ,during execution of any statement in the try block ,then
(ii) If the exception type matches the exception named after the except keyword ,the except block is
executed and then execution continues after the try statement.
(iii) If the exception occurs which does not match the exception named in the except block ,then it is
passed on to outer try block. If no exception handler is found in the program then it is an unhandled
exception and the program is terminated with an error message.
1. You are developing a Python program that reads an integer from the user and calculates the square
root of that number. However, the user might enter a negative number, which would result in a
ValueError.
2. You are developing a Python program that calculates the area of a rectangle. However, there is a
typo in one of the variable names used to store the width of the rectangle, leading to a NameError.
2. What type of error is raised when a function receives an argument of the correct type but an inappropriate
value?
a) SyntaxError b) ValueError c)NameError d) TypeError
3. What is the purpose of using a try-except block in Python?
a) To ignore any exceptions that occur during program execution. b) To catch and handle exceptions that occur
during program execution.
c) To terminate the program if an exception occurs. d) To raise a specific exception at a particular point in the
program.
except Exception2:
if there is Exception 2, then execute this block:
............................
else:
if there is no exception then execute this block
try:
num=int(input("Enter the number:"))
Output:
print(num**2)
. except(KeyboardInterrupt): Enter the number : abc
Please check before you
print("you should have entered a number.....Program
enter......Program Terminating....
Terminating...")
Bye
except(ValueError):
print("Please check before you enter......Program Terminating....")
print("Bye")
1. You are developing a Python program that reads a list of integers from a file and calculates the
average. However, the file might not exist, or it might contain non-integer values.
2. You are developing a Python program that calculates the average of a list of numbers. However,
the list might be empty or contain non-numeric values.
3. You are developing a Python program that divides two numbers provided by the user. However,
the user might enter invalid inputs, such as non-numeric values or zero as the divisor
1. You are developing a Python program that takes user input for two numbers and performs a
mathematical operation. However, the user might enter non-numeric values
2. You are developing a Python program that calculates the area of a rectangle based on user input
for length and width. However, the user might enter non-numeric values for length or width.
Syntax
try:
write the operations here
............................
except Exception1:
if there is any exception, then execute this block
else:
if there is no exception than execute this block.
1. Write a Python function that takes a list of numbers and an index as input, and returns the
element at the given index. If the index is out of bounds or the input is not a list, the function
should print "Invalid input" without specifying the type of exception.
2. Write a Python function that reads an integer from the user and computes the square root of the
integer. If the input is not an integer or the square root is not a real number, the function should
print "Error" without specifying the type of exception.
1. What will be the output if the user enters "abc" as input? try:
b) Result: 0 y = 10 / x
except:
c) No output, the program will raise an error
print("An error occurred")
d) Result: Infinity
else:
print("Result:", y)
try:
. file=open('DSU2.txt')
Output:
str1=file.readlines()
['Hello All, hope you are enjoying
print(str1)
learning python\n']
except IOError:
Program Terminating Successfully......
print("error occured during input.....Program terminating...")
else:
print("Program Terminating Succesfully......")
1. Write a Python function that takes a list of integers as input and returns the sum of all even
numbers in the list. If the list is empty or contains no even numbers, the function should return 0.
Use an else block to handle the case when no even numbers are found
2. Write a Python program that reads a list of student names and their corresponding scores from a
file. For each student, if the score is greater than or equal to 80, the program should print "Pass". If
the score is less than 80, the program should print "Fail". Use an else block to handle the case
when a score is exactly 80
▪Here Exception is the type of exception (for example, NameError) and argument is a
value for the exception argument. The argument is optional; if not supplied, the exception
argument is None.
▪The final argument, traceback, is also optional (and rarely used in practice), and, if
present, is the traceback object used for the exception
try:
num = 10
print(num)
raise ValueError Output:
except: 10
print("Exception Occurred.... Program Exception Occurred.... Program
Terminating") Terminating
▪It refers to the practice of catching an exception and then raising it again
def example_function(value):
try:
if value < 0:
raise ValueError("Value must be non-negative")
else:
print("Value is:", value)
except ValueError as ve: Output:
print(f"Caught an exception: {ve}")
raise Caught an exception: Value must be non-negative
# Example usage
Caught the re-raised exception: Value must be non-
try: negative
example_function(-5)
except ValueError as ve:
print(f"Caught the re-raised exception: {ve}")
print("Indented incorrectly")
▪ValueError: Raised when a function receives an argument of the correct type but an
inappropriate value.
int("abc")
content = file.read()
print(my_list[5])
print(my_dict["c"])
pass
obj = MyClass()
print(obj.attribute)
class MyError(Exception):
def __init__(self,val):
self.val = val
Output:
def __str__(self):
return repr(self.val) User Defined Exception
Generated With the Value : 10
try:
raise MyError(10)
except MyError as e:
print("User Defined Exception Generated With the Value : ", e.val)
▪The finally block is often used to perform cleanup or resource release operations,
ensuring that certain code is executed regardless of whether an exception occur
▪Finally block will perform the operations written in it and then re-raise the exception.
▪This exception will be handled by the except block if present in the next higher layer of
the try-except block.
Output:
try:
print("Dividing Strings.....") Dividing Strings.....
In finally block....
try:
In except block.... Handling TypeError...
quo = 'abc' / 'def'
finally:
print("In finally block....")
except TypeError:
print("In except block.... Handling TypeError...")
▪The default clean-up action is performed irrespective of whether the operation using the
object succeeded or failed.
▪The with statement is commonly used to define a clean-up action, particularly for
resources like files.
▪It simplifies resource management by ensuring that certain operations are performed
before and after a block of code.
▪Raising Exceptions:
▪Q: How do you raise a custom exception in Python?
▪a) raise CustomException()
▪b) throw CustomException()
▪c) throw Exception("Custom message")
▪d) raise Exception("Custom message")
▪Answer: a
▪User-Defined Exceptions:
▪Q: In Python, when creating a custom exception class, it is best practice to inherit from
which class?
▪a) Exception
▪b) Error
▪c) BaseException
▪d) CustomError
▪Answer: a
▪Answer: c
▪Answer: c
try:
example_function(-5)
except ValueError as ve:
print(f"Caught the re-raised exception: {ve}")
try:
result = int("abc")
except ValueError as ve:
print(f"Caught a ValueError: {ve}")
else:
print("Conversion successful")
finally:
print("Finally block executed")
def example_function(value):
if value == 42:
raise CustomError("The answer to life, the universe, and
everything")
else:
print("Value is:", value)
try:
example_function(42)
except CustomError as ce:
print(f"Caught a custom exception: {ce}")
finally:
print("Finally block executed")
try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found.")
finally:
file.close()
print("File closed")