0% found this document useful (0 votes)
12 views

OOP-PPT-Module 5 Part 2

Uploaded by

naikpoojitha33
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

OOP-PPT-Module 5 Part 2

Uploaded by

naikpoojitha33
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 60

OBJECT ORIENTED PROGRAMMING

UNIT-5 : ERROR AND EXCEPTION HANDLING

5/1/2024 1.0001 LECTURE 1 1


Error and Exception Handling
1.Introduction to Errors and Exceptions
Definition:

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

5/1/2024 1.0001 LECTURE 1 2


Error and Exception Handling
Logical Error
Errors
Abnormal or Syntactic Error
Unexpected
behavior of
program Synchronous
Exceptions
Asynchronous
Figure: Errors and Exceptions

5/1/2024 1.0001 LECTURE 1 3


Error and Exception Handling
The two common types of errors that we very often encounter are

⮚ Syntax Errors

⮚ Logical Errors

Syntax Error :arises due to the poor understanding of the language.

Logical Error : occur due to poor understanding of problem and solution.

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

5/1/2024 1.0001 LECTURE 1 4


Error and Exception Handling
Syntax Error arises due to the poor understanding of the language.

Example: syntax errors


i=0
if i== 0
print(i)
Syntax Error: Invalid Syntax
Logical Error occur due to poor understanding of problem and solution.

if a< b :
print(“a is bigger than b”)

5/1/2024 1.0001 LECTURE 1 5


Error and Exception Handling
Comparison of Syntax Error and Logical Error
Syntax Error Logical Error
Occurrence
Occur due to the poor understanding of the language Occur due to poor understanding of problem and
solution.

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/1/2024 1.0001 LECTURE 1 6


Error and Exception Handling
Exceptions : even if a statement is syntactically correct ,it may still cause an error when
executed such errors that occur at run time(or during execution) are known as exceptions.
Example:

>> 5/0
ZeroDivisionError: division by zero
>> var + 10
NameError: name 'var' is not defined

5/1/2024 1.0001 LECTURE 1 7


EXCERCISE
Unsolved Programming Question to be solved by students: Handle the following situations

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.

5/1/2024 1.0001 LECTURE 1 8


EXCERCISE
Quiz

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

5/1/2024 1.0001 LECTURE 1 9


EXCERCISE
Code snippet –Predict Output

1. What will be the output of the code snippet?


print("Hello, world!)

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

5/1/2024 1.0001 LECTURE 1 10


Error and Exception Handling
2. Handling Exceptions: We can handle exceptions in our program by using try block
and except block .

Syntax:
try:
statements
. except ExceptionName:
statements

5/1/2024 1.0001 LECTURE 1 11


Error and Exception Handling
The try statement works as follows
Step 1: First ,the try block (statement(s) between the try and except keywords is executed

Step 2a: If no exception occurs ,the except block is skipped.

Step 2b: If an exception occurs ,during execution of any statement in the try block ,then

(i) Rest of the try statements in the try block is skipped

(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.

5/1/2024 1.0001 LECTURE 1 12


Error and Exception Handling
Example : Program to handle the divide by zero exception

num=int(input(“Enter the numerator :"))


Output:
deno =int(input(“Enter the denominator :"))
. try: Enter the numerator : 10
enter the Denominator : 0
quo=num/deno
Denominator cannot be zero
print("QUOTIENT:",quo)
except ZeroDivisionError:
print("Denominator cannot be zero")

5/1/2024 1.0001 LECTURE 1 13


EXCERCISE
Unsolved Programming Questions to be handled by the students

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.

5/1/2024 1.0001 LECTURE 1 14


EXCERCISE
Quiz
1. Which keyword is used in Python to handle exceptions?
a) try b)catch c) finally d) throw

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.

5/1/2024 1.0001 LECTURE 1 15


EXCERCISE
Code snippet –Predict Output
try:
1.What will be the output of the code snippet?
a) Division successful. x = 10 / 0

b ) Division by zero! print("Division successful.")

c) The program will raise a ZeroDivisionError except ZeroDivisionError:

but will not print anything. print("Division by zero!")


d) The program will raise a ZeroDivisionError and terminate without printing anything.

5/1/2024 1.0001 LECTURE 1 16


Error and Exception Handling
3. Multiple Expect Blocks: Python allows to have multiple except block for a single try
block. The block which matches with the exception generated will get executed .

5/1/2024 1.0001 LECTURE 1 17


Error and Exception Handling
Syntax:
try:
operations are done in this block
............................
except Exception1:
if there is Exception 1, then execute this block:

except Exception2:
if there is Exception 2, then execute this block:
............................
else:
if there is no exception then execute this block

5/1/2024 1.0001 LECTURE 1 18


Error and Exception Handling
Example : Program with multiple except blocks

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")

5/1/2024 1.0001 LECTURE 1 19


EXCERCISE
Unsolved Programming Question to be handled by students

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

5/1/2024 1.0001 LECTURE 1 20


EXCERCISE
Quiz
1. Which of the following is true about using multiple except blocks in Python?
a) Each except block can handle multiple types of exceptions.
b) The order of except blocks is important, with more specific exceptions coming before more general ones.
c) except blocks cannot be used together with a finally block.
d) A try block can have only one corresponding except block.
2. What happens if an exception occurs that is not handled by any of the except blocks in a try-except
statement with multiple except blocks?
a) The program continues executing normally.
b) The program terminates with an unhandled exception error.
c) The program skips the try block and executes the finally block.
d) The program raises a syntax error

5/1/2024 1.0001 LECTURE 1 21


EXCERCISE
Code snippet –Predict Output try:
1. What will be the output of the code snippet? x = 10 / 'a'
a) ZeroDivisionError occurred! except ZeroDivisionError:
b) TypeError occurred! print("ZeroDivisionError occurred!")
c )Exception occurred! except TypeError:

d )The program will raise a TypeError and terminate. print("TypeError occurred!")


except Exception:
print("Exception occurred!")

5/1/2024 1.0001 LECTURE 1 22


Error and Exception Handling
4. Multiple Exception in single Block: An except clause may name multiple exceptions as a
parenthesized tuple.

Example : Program having an except clause handling multiple exception simultaneously


try:
num=int(input("Enter the number:")) Output:
print(num**2) Enter the number : abc
except(KeyboardInterrupt, ValueError, TypeError): Please check before you
print("Please check before you enter......Program enter......Program Terminating....
Terminating....") Bye
print("Bye")

5/1/2024 1.0001 LECTURE 1 23


EXCERCISE
Unsolved Programming Question for students

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.

5/1/2024 1.0001 LECTURE 1 24


EXCERCISE
Quiz
1. How can you handle multiple exceptions in a single except block in Python?
a) By using a comma-separated list of exception types
b) By using separate except blocks for each exception type
c) By using a finally block
d) By using a try block
2. Which keyword is used in Python to specify multiple exceptions in a single except block?
a) and
b) or
c) except
d) as

5/1/2024 1.0001 LECTURE 1 25


EXCERCISE
Code snippet –Predict Output
1. Is the following python code valid? try:

a) no, there is no such thing as else # Do something


b) no, else cannot be used with except except:
c) no, else must come before except
d) yes # Do something
else:
# Do something

5/1/2024 1.0001 LECTURE 1 26


Error and Exception Handling
5. Except block without Exception : can specify an except block without mentioning any
exception(i.e. except:)

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.

5/1/2024 1.0001 LECTURE 1 27


Error and Exception Handling
Example : Program to demonstrate the use of except block
try:
file=open('File1.txt')
. str1=f.readlines()
Output:
print(str1)
Unexpected error......Program
except IOError:
Terminating
print("error occured during input.....Program terminating...")
Except ValueError:
print(“could not convert data to an integer.”)
except:
print(“Unexpected error......Program Terminating…")

5/1/2024 1.0001 LECTURE 1 28


EXCERCISE
Unsolved Programming Question for students

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.

5/1/2024 1.0001 LECTURE 1 29


EXCERCISE
Quiz
1. Which of the following best describes the behavior of an except block without specifying the Exception
base class?
a) It handles only specific exceptions that are explicitly listed
b) It handles any type of exception without specifying the type
c) It raises an error if an exception occurs
d) It catches exceptions raised by the finally block
2. When should you use an except block without specifying the Exception base class?
a) When you want to handle all exceptions in the same way
b) When you want to handle specific exceptions separately
c) When you want to handle any type of exception without specifying the type
d) When you want to raise an error if an exception occurs

5/1/2024 1.0001 LECTURE 1 30


EXCERCISE
Code snippet –Predict Output

1. What will be the output if the user enters "abc" as input? try:

a ) An error occurred x = int(input("Enter a number: "))

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)

5/1/2024 1.0001 LECTURE 1 31


Error and Exception Handling
6. The else Clause :The try… except block can optionally have an else clause .which ,when present
must follow all except blocks .The statement(s) in the else block is executed only if the try clause
does not raise an exception 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.

5/1/2024 1.0001 LECTURE 1 32


EXCERCISE
Example : Program to demonstrate the else block

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......")

5/1/2024 1.0001 LECTURE 1 33


EXCERCISE
Unsolved Programming Question for students

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

5/1/2024 1.0001 LECTURE 1 34


EXCERCISE
Quiz
1. What is the purpose of the else block in a try-except statement in Python?
a) It always executes after the try block
b) It executes if an exception occurs in the try block
c) It executes if no exception occurs in the try block
d) It executes if the except block is skipped
2. When is the else block executed in a try-except statement?
a) When an exception occurs in the try block
b) When no exception occurs in the try block
c) When an exception occurs in the except block
d) When no except block is specified

5/1/2024 1.0001 LECTURE 1 35


EXCERCISE
Code snippet –Predict Output
1. What will be the output ?
try:
a) Hello
print("Hello")
b) Something went wrong
except:
c) Hello , Nothing went wrong print("Something went wrong")
d) Hello, Something went wrong else:
print("Nothing went wrong")

5/1/2024 1.0001 LECTURE 1 36


EXCERCISE
Code snippet –Predict Output
while True:
1. Predict the output for the following inputs: x = int(input())
a) Input: 0 try:

b) Input: 2 result = 1/x


except:
c) Input: a (non-integer input)
print("Error case")
d) Input: 5 exit(0)
. else:

a)Error case b)Pass case c)ValueError d)Pass case print("Pass case")


exit(1)

5/1/2024 1.0001 LECTURE 1 37


Raising Exception
▪ Exceptions can be raised using “raise” key word.

▪ Syntax : raise [Exception [, args [, traceback]]]

▪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

5/1/2024 1.0001 LECTURE 1 38


Raising Exception

▪Solved programming example

try:
num = 10
print(num)
raise ValueError Output:

except: 10
print("Exception Occurred.... Program Exception Occurred.... Program
Terminating") Terminating

5/1/2024 1.0001 LECTURE 1 39


Re - Raising Exception
▪Exception can be re raised in the except: block

▪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}")

5/1/2024 1.0001 LECTURE 1 40


Built-in Exception
▪Python provides a variety of built-in exceptions that cover a wide range of potential
errors.

▪SyntaxError: Raised when there is a syntax error in the code.


print "Hello, World!"

▪IndentationError: Raised when there is an incorrect indentation.


if True:

print("Indented incorrectly")

5/1/2024 1.0001 LECTURE 1 41


Built-in Exception
▪NameError: Raised when a local or global name is not found.
print(undefined_variable)

▪TypeError: Raised when an operation or function is applied to an object of an


inappropriate type.
result = "2" + 2

▪ValueError: Raised when a function receives an argument of the correct type but an
inappropriate value.
int("abc")

5/1/2024 1.0001 LECTURE 1 42


Built-in Exception
▪ZeroDivisionError: Raised when division or modulo by zero is encountered.
result = 10 / 0

▪FileNotFoundError: Raised when a file or directory is requested but cannot be found.


with open("nonexistent_file.txt", "r") as file:

content = file.read()

▪IndexError: Raised when a sequence subscript is out of range.


my_list = [1, 2, 3]

print(my_list[5])

5/1/2024 1.0001 LECTURE 1 43


Built-in Exception
▪KeyError: Raised when a dictionary key is not found.
my_dict = {"a": 1, "b": 2}

print(my_dict["c"])

▪AttributeError: Raised when an attribute reference or assignment fails.


class MyClass:

pass

obj = MyClass()

print(obj.attribute)

5/1/2024 1.0001 LECTURE 1 44


User Defined Exception
▪ Own custom exceptions can be created by defining new classes that inherit from the built-in Exception
class or one of its subclasses. This allows you to raise and catch exceptions tailored to the specific needs
of your program.

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)

5/1/2024 1.0001 LECTURE 1 45


Finally Block
▪The finally block is used in conjunction with the try and except blocks to define a set of
statements that will be executed whether an exception is raised or not.

▪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

▪Else block with finally block is not allowed.

5/1/2024 1.0001 LECTURE 1 46


Finally Block
try:
# Code that may raise an exception
result = 10 / 0
except ZeroDivisionError: Output:
# Code to handle the specific exception
print("Cannot divide by zero.") Cannot divide by zero.
finally: This will be executed no matter
# Code that will always be executed, regardless of what.
whether an exception occurs or not
print("This will be executed no matter what.")

5/1/2024 1.0001 LECTURE 1 47


Finally Block
▪for resource cleanup.
try:
file = open("example.txt", "r")
# Code that may raise an exception while reading from the file
content = file.read()
except FileNotFoundError:
print("File not found.")
finally:
# Ensure that the file is closed, whether an exception occurred
or not
file.close()

5/1/2024 1.0001 LECTURE 1 48


Finally Block
▪If finally block is placed immediately after the try block and followed by the except block,
then if an exception is raised in the try block, the code in finally will be executed first.

▪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.

5/1/2024 1.0001 LECTURE 1 49


Finally 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...")

5/1/2024 1.0001 LECTURE 1 50


Clean up Action
▪In Python, some objects define standard clean-up actions that are automatically
performed when the object is no longer needed.

▪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.

5/1/2024 1.0001 LECTURE 1 51


Clean up Action
▪In this example, the with statement ensures that the file is properly closed after reading
its content.
Equivalent code:
# Using with statement for file handling
with open("example.txt", "r") as file: file = open("example.txt", "r")
content = file.read() try:
# Do something with the file content content = file.read()
# Do something with the file content
# File is automatically closed outside the with block finally:
# Clean-up action is performed, even if an exception file.close()
occurs

5/1/2024 1.0001 LECTURE 1 52


EXERCISE
▪Quiz

▪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

5/1/2024 1.0001 LECTURE 1 53


EXERCISE
▪Quiz

▪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

5/1/2024 1.0001 LECTURE 1 54


EXERCISE
▪Quiz

▪4. Finally Block:


▪Q: What is the primary purpose of the finally block in a try-except-finally construct?
▪a) To catch and handle exceptions
▪b) To execute code only when an exception occurs
▪c) To ensure that certain code is executed regardless of whether an exception is raised or
not
▪d) To indicate the final statement of a program

▪Answer: c

5/1/2024 1.0001 LECTURE 1 55


EXERCISE
▪Quiz

▪5. Cleanup Action:


▪Q: When might you use a finally block for cleanup actions?
▪a) Only when an exception is raised
▪b) Only when no exception is raised
▪c) Always, regardless of whether an exception is raised or not
▪d) Only when handling specific exceptions

▪Answer: c

5/1/2024 1.0001 LECTURE 1 56


EXERCISE
▪Code snippet – predict output
def example_function(value):
try:
if value < 0:
raise ValueError("Value must be non-negative")
else:
print("Value is:", value)
except ValueError as ve:
print(f"Caught an exception: {ve}")
raise

try:
example_function(-5)
except ValueError as ve:
print(f"Caught the re-raised exception: {ve}")

5/1/2024 1.0001 LECTURE 1 57


EXERCISE
▪Code snippet – predict output

try:
result = int("abc")
except ValueError as ve:
print(f"Caught a ValueError: {ve}")
else:
print("Conversion successful")
finally:
print("Finally block executed")

5/1/2024 1.0001 LECTURE 1 58


EXERCISE
▪Code snippet – predict output class CustomError(Exception):
pass

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")

5/1/2024 1.0001 LECTURE 1 59


EXERCISE
▪Code snippet – predict output

try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found.")
finally:
file.close()
print("File closed")

5/1/2024 1.0001 LECTURE 1 60

You might also like