Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
EXCEPTION HANDLING
E-content Developed By: Shilpa S Surulkar, Assistant
Professor, Smt. K. G. Shah Dept. of Computer
Applications, Dr. BMN College of Home Science
Special Outreach sessions in view of closure of college on
account of COVID-19 Advisory
1
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
ERRORS AND EXCEPTION
Errors are the 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 changes the normal flow of the program.
A Python exception is a construct used to signal an important event, usually an
error, that occurs when executing a program. An exception may cause the
program to stop if it is not properly "caught" (i.e. handled correctly). If you think
that your program might raise an exception when executed, you will find it
useful to use try/except to handle them
2
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
HANDLING EXCEPTION
It is possible to write programs that handle selected exceptions. Exception
handling makes your code more robust and helps prevent potential failures
that would cause your program to stop in an uncontrolled manner. Imagine if
you have written a code which is deployed in production and still, it terminates
due to an exception, your client would not appreciate that, so it's better to
handle the particular exception beforehand and avoid the chaos.
3
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
HANDLING EXCEPTION
Exception handling increases the robustness of your code, which guards against
potential failures that would cause your program to exit in an uncontrolled fashion.
Before we get into why exception handling is essential and types of built-in exceptions
that Python supports, it is necessary to understand that there is a subtle difference
between an error and an exception.
4
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
COMPONENTS OF EXCEPTION
HANDLING
● Try: It will run the code block in which you expect an error to occur.
● Except: Here, you will define the type of exception you expect in the try block
(built-in or custom).
● Else: If there isn't any exception, then this block of code will be executed
(consider this as a remedy or a fallback option if you expect a part of your script to
produce an exception).
● Finally: Irrespective of whether there is an exception or not, this block of code
will always be executed.
5
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
HANDLING EXCEPTION
Example:
try:
print(x)
except:
print("An exception occurred")
6
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
HANDLING EXCEPTION
Example:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
7
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
HANDLING EXCEPTION
Example:
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
8
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
HANDLING EXCEPTION
Example:
def simple_div(x,y):
try:
z= x/y
except NameError:
z=-1
return z
simple_div(2,a)
9
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
HANDLING EXCEPTION
Example:
while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")
10
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
BUILT-IN EXCEPTION
Exception Cause of Error
AssertionError Raised when assert statement fails.
AttributeError Raised when attribute assignment or reference fails.
EOFError Raised when the input() functions hits end-of-file
condition.
FloatingPointError Raised when a floating point operation fails.
GeneratorExit Raise when a generator's close() method is called.
ImportError Raised when the imported module is not found.
IndexError Raised when index of a sequence is out of range.
KeyError Raised when a key is not found in a dictionary.
KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or
delete).
MemoryError Raised when an operation runs out of memory.
NameError Raised when a variable is not found in local or global
scope.
11
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
BUILT-IN EXCEPTION
Exception Cause of Error
NotImplementedError Raised by abstract methods.
OSError Raised when system operation causes system related
error.
OverflowError Raised when result of an arithmetic operation is too
large to be represented.
ReferenceError Raised when a weak reference proxy is used to access a
garbage collected referent.
RuntimeError Raised when an error does not fall under any other
category.
StopIteration Raised by next() function to indicate that there is no
further item to be returned by iterator.
SyntaxError Raised by parser when syntax error is encountered.
IndentationError Raised when there is incorrect indentation.
12
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
BUILT-IN EXCEPTION
Exception Cause of Error
TabError Raised when indentation consists of inconsistent tabs
and spaces.
SystemError Raised when interpreter detects internal error.
SystemExit Raised by sys.exit() function.
TypeError Raised when a function or operation is applied to an
object of incorrect type.
UnboundLocalError Raised when a reference is made to a local variable in a
function or method, but no value has been bound to that
variable.
UnicodeError Raised when a Unicode-related encoding or decoding
error occurs.
UnicodeEncodeError Raised when a Unicode-related error occurs during
encoding.
13
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
BUILT-IN EXCEPTION
Exception Cause of Error
UnicodeDecodeError Raised when a Unicode-related error occurs during
decoding.
UnicodeTranslateError Raised when a Unicode-related error occurs during
translating.
ValueError Raised when a function gets argument of correct type
but improper value.
ZeroDivisionError Raised when second operand of division or modulo
operation is zero.
14
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
RAISING AN EXCEPTIONS
To throw (or raise) an exception, use the raise keyword. The raise keyword is
used to raise an exception.
Example:
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
Output:
Traceback (most recent call last):
File "demo_ref_keyword_raise.py", line 4, in <module>
raise Exception("Sorry, no numbers below zero")
Exception: Sorry, no numbers below zero
15
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
RAISING AN EXCEPTIONS
Example:
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
Output:
Traceback (most recent call last):
File "demo_ref_keyword_raise2.py", line 4, in <module>
raise TypeError("Only integers are allowed")
TypeError: Only integers are allowed
16
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
EXCEPTION WITH ARGUMENTS
An exception can have an argument, which is a value that gives additional information
about the problem. The contents of the argument vary from exception to exception.
You capture an exception's argument by supplying a variable in the except clause as
follows
Example:
try:
b=float (56+78/0)
except Exception as Argument:
print (“This is the Argument\n”, Argument)
Output:
This is the Argument
Integer division or modulo by zero
●
17
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
EXCEPTION WITH ARGUMENTS
Example:
my_string = "GeeksForGeeks"
try:
b = float(my_string / 20)
except Exception as Argument:
print( 'This is the Argument\n', Argument)
Output:
This is the Argument
unsupported operand type(s) for /: 'str' and 'int'
●
18
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
WHY USE ARGUMENTS IN
EXCEPTIONS
Using arguments for Exceptions in Python is useful for the following reasons:
● It can be used to gain additional information about the error encountered.
● As contents of an Argument can vary depending upon different types of
Exceptions in Python, Variables can be supplied to the Exceptions to
capture the essence of the encountered errors. Same error can occur of
different causes, Arguments helps us identify the specific cause for an error
using the except clause.
● It can also be used to trap multiple exceptions, by using a variable to follow
the tuple of Exceptions.
19
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
USER-DEFINED EXCEPTIONS
A user can create his own error using exception class. Programs may name their own
exceptions by creating a new exception class. Exceptions should typically be derived
from the Exception class, either directly or indirectly. Although not mandatory, most of
the exceptions are named as names that end in “Error” similar to naming of the
standard exceptions in python.
20
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
USER-DEFINED EXCEPTIONS
Example:
# define Python user-defined exceptions
class Error(Exception):
"""Base class for other exceptions"""
pass
class Dividebyzero(Error):
"""Raised when the input value is zero"""
pass
try:
i_num = int(input("Enter a number: "))
if i_num ==0:
raise Dividebyzero
except Dividebyzero:
print("Input value is zero, try again!")
print()
21
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
USER-DEFINED EXCEPTIONS
Example:
# define Python user-defined exceptions
class Error(Exception):
"""Base class for other exceptions"""
pass
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass
class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass
# you need to guess this number
number = 10
# user guesses a number until he/she gets it right
22
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
USER-DEFINED EXCEPTIONS
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, try again!")
print()
except ValueTooLargeError:
print("This value is too large, try again!")
print()
print("Congratulations! You guessed it correctly.")
23
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
Stay Home, Stay Safe #fightagainstcorona
24
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
CONCEPT OF REGULAR EXPRESSION
A regular expression is a special sequence of characters that helps you
match or find other strings or sets of strings, using a specialized syntax held in
a pattern. Regular expressions are widely used in UNIX world. The Python
module re provides full support for Perl-like regular expressions in Python. The
re module raises the exception re.error if an error occurs while compiling or
using a regular expression. We would cover two important functions, which
would be used to handle regular expressions. But a small thing first: There are
various characters, which would have special meaning when they are used in
regular expression. To avoid any confusion while dealing with regular
expressions, we would use Raw Strings as r'expression'.
25
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
CONCEPT OF REGULAR EXPRESSION
When you have imported the re module, you can start using regular expressions:
Example (Search the string to see if it starts with "The" and ends with "Spain"):
import re
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
26
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
VARIOUS TYPES OF REGULAR
EXPRESSIONS
RegEx Functions: The re module offers a set of functions that allows us to search a
string for a match:
Function Description
findall Returns a list containing all matches
search Returns a Match object if there is a match anywhere in the string
split Returns a list where the string has been split at each match
sub Replaces one or many matches with a string
27
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
VARIOUS TYPES OF REGULAR
EXPRESSIONS
Metacharacters: Metacharacters are characters with a special meaning:
Character Description Example
[] A set of characters "[a-m]"
\ Signals a special sequence (can also be used to escape "\d"
special characters)
. Any character (except newline character) "he..o"
^ Starts with "^hello"
$ Ends with "world$"
* Zero or more occurrences "aix*"
+ One or more occurrences "aix+"
{} Exactly the specified number of occurrences "al{2}"
| Either or "falls|stays
"
() Capture and group
28
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
VARIOUS TYPES OF REGULAR
EXPRESSIONS
Special Sequences: A special sequence is a \ followed by one of the characters in
the list below, and has a special meaning:
Character Description Example
\A Returns a match if the specified characters are at the "\AThe"
beginning of the string
\b Returns a match where the specified characters are at the r"\bain"
beginning or at the end of a word r"ain\b"
\B Returns a match where the specified characters are r"\Bain"
present, but NOT at the beginning (or at the end) of a r"ain\B"
word
\d Returns a match where the string contains digits "\d"
(numbers from 0-9)
\D Returns a match where the string DOES NOT contain "\D"
digits
\s Returns a match where the string contains a white space "\s"
character
29
Dr. BMN College of Home Science (Autonomous) || NAAC A+ Grade with 3.69/4 CGPA || Smt. K. G.
Shah Dept. of Computer Applications || 30th April 2020
VARIOUS TYPES OF REGULAR
EXPRESSIONS
Special Sequences: A special sequence is a \ followed by one of the characters in
the list below, and has a special meaning:
Character Description Example
\S Returns a match where the string DOES NOT contain a "\S"
white space character
\w Returns a match where the string contains any word "\w"
characters (characters from a to Z, digits from 0-9, and
the underscore _ character)
\W Returns a match where the string DOES NOT contain "\W"
any word characters
\Z Returns a match if the specified characters are at the end "Spain\Z"
of the string
30