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

Python Exception Handling

• Error in Python can be of two types


i) Syntax errors
ii) Exceptions.
• Errors are problems in a program due to
which the program will stop the execution.
• On the other hand, exceptions are raised
when some internal events occur which
change the normal flow of the program.
Different types of exceptions in python:

Several built-in Python exceptions that can be raised when an error occurs during the
execution of a program.

• 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.
• Exceptions: Exceptions are raised when the
program is syntactically correct, but the code
results in an error.

• This error does not stop the execution of the


program, however, it changes the normal flow
of the 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.

Example
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
finally:
print("The 'try except' is finished")
Catching Specific Exception
A try statement can have more than one
except clause, to specify handlers for different
exceptions.

try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)
def fun(a):
if a < 4:

b = a/(a-3)
print("Value of b = ", b)

try:
fun(3)
fun(5)
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")
Raise an exception
• As a Python developer you can choose to
throw an exception if a condition occurs.
• To throw (or raise) an exception, use
the raise keyword.

Example:
x = -1

if x < 0:
raise Exception("Sorry, no numbers below zero")
• The raise statement allows the programmer to
force a specific exception to occur. The sole
argument in raise indicates the exception to
be raised.
Example:
try:
raise NameError("Hi there")
Output:
except NameError: Traceback (most recent call last):
File
print ("An exception") "/home/d6ec14ca595b97bff8d8034bbf
212a9f.py", line 5, in <module>
raise raise NameError("Hi there") # Raise
Error
NameError: Hi there
try:
x = 10
y="xyz"
z=x/y
except ZeroDivisionError:
print("except ZeroDivisionError block") print("Division by 0 not
accepted")
except:
print('Error occurred.')
else:
print("Division = ", z)
finally:
print("Executing finally block") x=0 y=0 print ("Out of try, except,
else and finally blocks." )
Assertions in Python
• Assertions are mainly assumptions that a
programmer knows or always wants to be true and
hence puts them in code so that failure of these
doesn’t allow the code to execute further.

• assertion is the boolean expression that checks if the


statement is True or False.

• If the statement is true then it does nothing and


continues the execution, but if the statement is False
then it stops the execution of the program and
throws an error.
Assertions in Python

• The simplest way to understand an assertion is to compare it


with an if-then condition. An exception is thrown if the
outcome is false when an expression is evaluated.

• Assertions are made via the assert statement, which was


added in Python 1.5 as the latest keyword.

• Assertions are commonly used at the beginning of a function


to inspect for valid input and at the end of calling the function
to inspect for valid output.
The assert Statement
• Python examines the adjacent expression, preferably true
when it finds an assert statement. Python throws an
AssertionError exception if the result of the expression is
false.

• The syntax for the assert clause is −


assert condition, error_message(optional)

Parameters:
condition : The boolean condition returning true or false.
error_message : The optional argument to be printed in console
in case of AssertionError
# initializing number
a=4
b=0
Output:

# using assert to check for 0 The value of a / b is :


print("The value of a / b is : ") AssertionError
Traceback (most recent call last)
assert b != 0 Input In [19], in <cell line: 10>()
print(a / b) 8 # using assert to check for 0
9 print("The value of a / b is : ")
---> 10 assert b != 0

11 print(a / b)
AssertionError:
# Python 3 code to demonstrate
# working of assert

# initializing number
a=4
Output:
b=0 AssertionError: Zero Division Error

# using assert to check for 0


print("The value of a / b is : ")
assert b != 0, "Zero Division Error"
print(a / b)
Example : Using assert with error message
def avg(marks):
assert len(marks) != 0,"List is empty."
return sum(marks)/len(marks) Output:

Average of mark2: 78.0


AssertionError: List is
mark2 = [55,88,78,90,79] empty.
print("Average of mark2:",avg(mark2))

mark1 = []
print("Average of mark1:",avg(mark1))
#Python program to show how to use assert keyword
# defining a function
def square_root( Number ):
assert ( Number < 0), "Give a positive integer"
return Number**(1/2)

#Calling function and passing the values


print( square_root( 36 ) )
print( square_root( -36 ) )
Output:

7 #Calling function and passing the values


----> 8 print( square_root( 36 ) )
9 print( square_root( -36 ) ) Input In [23], in
square_root(Number)

3 def square_root( Number ):


----> 4 assert ( Number < 0), "Give a positive integer"
5 return Number**(1/2) AssertionError: Give a
positive integer
Why Use Python Assert Statement?

1. Debugging: Assumptions made by your code can be verified


with the assert statement.
2. Documentation: The use of assert statements in your code
might act as documentation. Assert statements make it
simpler for others to understand and work with your code
since they explicitly describe the assumptions that your code
is making.
3. Testing: In order to ensure that certain requirements are
met, assert statements are frequently used in unit testing.
4. Security: You can use assert to check that program inputs
comply with requirements and validate them.

You might also like