2. Python Errors and Exceptions
• Encountering errors and exceptions can be very frustrating at times,
and can make coding feel like a hopeless endeavor.
• However, understanding what the different types of errors are and
when you are likely to encounter them can help a lot.
• Python Errors can be of three types:
1.Compile time errors (Syntax errors)
2.Runtime errors (Exceptions)
3.Logical errors
06-04-2022 meghav@kannuruniv.ac.in 2
3. • Compile time errors (Syntax errors)
• Errors caused by not following the proper structure (syntax) of the
language are called syntax or parsing errors.
• Runtime errors (Exceptions)
• Exceptions occur during run-time.
• Your code may be syntactically correct but it may happen that during
run-time Python encounters something which it can't handle , then it
raises an exception.
06-04-2022 meghav@kannuruniv.ac.in 3
4. • Logical errors
• Logical errors are the most difficult to fix.
• They occur when the program runs without crashing, but produces
an incorrect result.
• The error is caused by a mistake in the program's logic .
• You won't get an error message, because no syntax or runtime error
has occurred.
06-04-2022 meghav@kannuruniv.ac.in 4
5. Python Exception Handling
• The try block lets you test a block of code for errors.
• The except block lets you handle the error.
• The finally block lets you execute code, regardless of the result of the
try- and except blocks.
• When an error occurs, or exception as we call it, Python will normally
stop and generate an error message.
06-04-2022 meghav@kannuruniv.ac.in 5
6. Python Exception Handling
• These exceptions can be handled using the try statement:
• Example
• The try block will generate an exception, because x is not defined:
try:
print(x)
except:
print("An exception occurred")
06-04-2022 meghav@kannuruniv.ac.in 6
7. • Since the try block raises an error, the except block will be
executed.
• Without the try block, the program will crash and raise an
error:
Example
• This statement will raise an error, because x is not defined:
print(x)
06-04-2022 meghav@kannuruniv.ac.in 7
9. Except clause with multiple exceptions
try:
a=int(input(“First Number:”))
b=int(input(“Second Number:”))
result=a/b
print(“Result=”,result)
except(ZeroDivisionError, TypeError):
print(“Error occurred”)
else:
print(“Successful Division”)
Output
First Number:10
Second Number:0
Error occured
06-04-2022 meghav@kannuruniv.ac.in 9
10. try......finally
• A finally block can be used with a try block
• The code placed in the finally block is executed no matter Exception is
caused or caught
• We cannot use except clause and finally clause together with a try block
• It is also not possible to use else clause and finally together with try block.
Syntax:
try:
suite;
finally:
finally_suite # Executed always after the try block
06-04-2022 meghav@kannuruniv.ac.in 10
12. Some of the common in-built exceptions are as follows:
1.ZeroDivisionError -Raised when division or modulo by zero takes place for all
numeric types.
2.NameError - Raised when name of keywords, identifiers..etc are wrong
3.IndentationError - Raised when indentation is not properly given
4.IOError - Raised when an input/ output operation fails, such as the print
statement or the open() function when trying to open a file that does not exist.
5.EOFError - Raised when there is no input from either the raw_input() or input()
function and the end of file is reached.
06-04-2022 meghav@kannuruniv.ac.in 12
13. Python - Assert Statement
• In Python, the assert statement is used to continue the execute if the given condition
evaluates to True.
• If the assert condition evaluates to False, then it raises the AssertionError exception
with the specified error message.
Syntax
assert condition [, Error Message]
• The following example demonstrates a simple assert statement.
Example:
x = 10
assert x > 0
print('x is a positive number.')
Output
• x is a positive number.
• In the above example, the assert condition, x > 0 evaluates to be True, so it will
continue to execute the next statement without any error.
06-04-2022 meghav@kannuruniv.ac.in 13
14. • The assert statement can optionally include an error message string, which
gets displayed along with the AssertionError.
• Consider the following assert statement with the error message.
Example: Assert Statement with Error Message
x = 0
assert x > 0, 'Only positive numbers are allowed’
print('x is a positive number.')
Output
Traceback (most recent call last):
assert x > 0, 'Only positive numbers are allowed'
AssertionError: Only positive numbers are allowed
06-04-2022 meghav@kannuruniv.ac.in 14
15. Python Program for User-defined Exception
Handling:
class YourException(Exception):
def __init__(self, message):
self.message = message
try:
raise YourException("Something is wrong")
except YourException as err:
# perform any action on YourException instance
print("Message:", err.message)
06-04-2022 meghav@kannuruniv.ac.in 15
17. Cont..
#Main Program
number=10
while True:
try:
i_num=int(input(“Enter a number:”))
if i_num<number:
raise ValueTooSmallError
elif i_num>number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print(“This value is too small ! Please try again”)
except ValueTooLargeError:
print(“This value is too large! Please try again”)
print(“Congratulations…You guesses it correctly”)
06-04-2022 meghav@kannuruniv.ac.in 17
18. Logging the exceptions
• Logging is a means of tracking events that happen when some software
runs.
• Logging is important for software developing, debugging, and running.
• To log an exception in Python we can use logging module and through
that we can log the error.
• Logging module provides a set of functions for simple logging and for
following purposes
• DEBUG
• INFO
• WARNING
• ERROR
• CRITICAL
06-04-2022 meghav@kannuruniv.ac.in 18
19. Logging the exceptions
• Logging an exception in python with an error can be done in
the logging.exception() method.
• This function logs a message with level ERROR on this logger.
• The arguments are interpreted as for debug().
• Exception info is added to the logging message.
• This method should only be called from an exception handler.
06-04-2022 meghav@kannuruniv.ac.in 19
20. Example:
06-04-2022 meghav@kannuruniv.ac.in 20
# importing the module
import logging
try:
printf(“Good Morning")
except Exception as Argument:
logging.exception("Error occurred while printing Good Morning")