KEMBAR78
Exception Handling in python programming.pptx
Exception
• When writing a program we more often than not will encounter errors.
• Error caused by not following the proper structure (syntax) of the
language is called syntax error parsing error.
>>> if a<3
Syntax Error: invalid syntax
• We can notice here that a colon is missing in the if statement.
• Errors can also occur at runtime and these are called exceptions
• They occur for example
– When a file we try to open does not exist (FileNotFoundError)
– Dividing a number by Zero (ZeroDivisionError)
– Module we try to import is not found (ImportError) etc.
• Whenever these type of runtime error occur, Python creates an exception
object. If not handled properly it prints a traceback to that error along
with some details about why that error occurred.
Exception
>>> 1/0
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
1/0
ZeroDivisionError: division by zero
>>> open('i.txt')
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
open('i.txt')
FileNotFoundError: [Errno 2] No such file or directory: 'i.txt'
Built-in Exceptions
• An exception is a value (object) that is raised (“thrown”) signaling that an
unexpected or “exceptional” situation has occurred.
• Python contains a predefined set of exceptions referred to as Standard
Exceptions.
Exceptions Description
ImportError Raised when an import (or from … import) statement fails
IndexError Raised when a sequence index out of range
NameError Raised when a local or global name is not found
TypeError Raised when an operation or function is applied to an
object of inappropriate type
ValueError Raised when a built in operation or function is applied to
an appropriate type, but of inappropriate value
IOError Raised when an input/output operation fails (eg: “file not
found”)
Standard Exceptions
• The standard exceptions are defined within the exceptions module of the
python standard library, which is automatically imported into python
programs.
• We have seen a number of these exceptions before in our programming.
• Raising an exception is a way for a function to inform its client a problem has
occurred that the function itself cannot handle.
>>> lst[3]
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
lst[3]
IndexError: list index out of range
>>> lst1[0]
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
lst1[0]
NameError: name 'lst1' is not defined
>>> int('45')
45
>>> 3+'7'
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
3+'7'
TypeError: unsupported operand type(s) for +:
'int' and 'str‘
>>> int('45.9')
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
int('45.9')
ValueError: invalid literal for int() with base 10:
'45.9'
The propagation of raised exceptions
• Raised exceptions are not required to be handled in python.
• When an exception is raised and not handled by the client code, it is
automatically propagated back to the clients calling code (and its calling
code etc) until handled.
• If an exception is thrown all the way back to the top level (main module)
and not handled, then the program terminates and displays the details of
the exception as shown below.
The propagation of raised exceptions
• If function A calls function B which in turn calls function C and which in
turn calls function D and an exception occurs in function D, if it is not
handled in D, the exception passes to C and then to B and then to A.
• If never handled an error message is split out and program come to a
sudden unexcepted halt.
Exception Handling
• Catching Exception:
– In python, exception can be handled using a try statement.
– A critical operation which can raise exception is placed inside the try clause and the code
that handles exception is written in except clause.
– It is upto us what operations we perform once we have caught the exception.
import sys
lst = ['x',5,0]
for e in lst:
try:
print("The element is ",e)
r = 1 / int(e)
print("The reciprocal of ", e," is ",r)
except:
print("Oops! ", sys.exc_info()[0],"
occurred")
OUTPUT:
The element is x
Oops! <class 'ValueError'> occurred
The element is 5
The reciprocal of 5 is 0.2
The element is 0
Oops! <class 'ZeroDivisionError'>
occurred
sys.exc_info()
• This function returns a tuple of three values that give information about
the exception that is currently being handled.
• The information returned is specific both to the current thread and to the
current stack frame.
• If the current stack frame is not handling an exception, the information is
taken from the calling stack frame or its caller and so in until a stack frame
is found that is handling an exception.
• Here “handling an exception” is defined as “executing or having executed
an except clause”.
• If no exception is being handled anywhere on the stack, a tuple containing
three None values is returned.
• Otherwise, the values returned on (type, value, traceback)
– type:- gets the exception type of the exception being handled (a class object)
– value:- gets the exception parameter
– traceback:- gets a traceback object
Exception Handling
import sys
lst = ['x',5,0]
for e in lst:
try:
print("The element is ",e)
r = 1 / int(e)
print("The reciprocal of ", e," is ",r)
except:
print("Oops! ", sys.exc_info(),"
occurred")
OUTPUT:
The element is x
Oops! (<class 'ValueError'>,
ValueError("invalid literal for int() with
base 10: 'x'"), <traceback object at
0x000001A994DFA4C8>) occurred
The element is 5
The reciprocal of 5 is 0.2
The element is 0
Oops! (<class 'ZeroDivisionError'>,
ZeroDivisionError('division by zero'),
<traceback object at
0x000001A994DFA4C8>) occurred
• If no exception occurs, except block is skipped and normal flow continues.
• But if any exception occurs it is caught by the except block.
The try and except block
• In python, exceptions are handled using the try and except block.
• Python, executes the try block as a normal part of the program.
• When an error occurs during its exception, the rest of the block is skipped
and except block is executed.
Example 1:
i=1/0
print("i = ",i)
print("After division")
Traceback (most recent call last):
File
"C:/Users/swathy/AppData/Local/Programs/Pyt
hon/Python37/files1.py", line 1, in <module>
i=1/0
ZeroDivisionError: division by zero
Exception Handling - Example
Example 2:
try:
i=1/0
print("i = ",i)
except:
print("Some exception occured")
print("After division")
OUTPUT:
Some exception occured
After division
import sys
try:
i=1/0
print("i = ",i)
except:
print(sys.exc_info()[0]," occured.")
print("After division")
OUTPUT:
<class 'ZeroDivisionError'> occured.
After division
Example 3:
Exception Handling - Example
• Python don’t just handle exceptions if they occur immediately in the try
block, but also if they occur inside functions that are called in the try
block.
import sys
def func():
i=1/0
print("Inside function")
try:
func()
print("Inside try block")
except:
print(sys.exc_info()[0]," occured.")
print("After function call inside main module")
OUTPUT:
<class 'ZeroDivisionError'> occured.
After function call inside main module
Example 4:
Catch Multiple Exceptions
• We can define as many except blocks as we want to catch and handle
specific exceptions.
try:
print(int('45.6'))
except (ZeroDivisionError, ValueError):
print("Attempt to divide by zero")
except:
print("Something else went wrong")
OUTPUT:
Attempt to divide by zero
ZeroDivisionError, ValueError
Example 4:
The Else Clause
• The try except block has an optional else clause.
• The else clause is executed only if no exceptions are raised
Example:
try:
x = 1/2
print("x = ",x)
except:
print("Something went wrong")
else:
print("Nothing went wrong")
x = 0.5
Nothing went wrong
The Finally Clause
• The try except block has an optional finally clause.
• The finally clause is always executed, whether an exception has occurred or not
The Finally Clause
• We can define as many except blocks as we want to catch and handle
specific exceptions.
try:
x = 1/0
except:
print("Something went wrong")
finally:
print("Always executes this")
OUTPUT:
Something went wrong
Always executes this
Example:
Example:
try:
f=open('text1.txt')
print(f.read())
except:
print("Something went wrong")
finally:
f.close()
OUTPUT:
Something went wrong
Always executes this
Raising an Exception
• If we want to raise an exception when a certain condition occurs, use raise
keyword.
• You can define what kind of error to raise, and the text to print to the user.
print("Exception handling concepts")
raise NameError("An exception occured")
Example:
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
OUTPUT:
Traceback (most recent call last):
File "keyword_raise.py", line 4, in
<module>
raise TypeError("Only integers are
allowed")
TypeError: Only integers are allowed

Exception Handling in python programming.pptx

  • 1.
    Exception • When writinga program we more often than not will encounter errors. • Error caused by not following the proper structure (syntax) of the language is called syntax error parsing error. >>> if a<3 Syntax Error: invalid syntax • We can notice here that a colon is missing in the if statement. • Errors can also occur at runtime and these are called exceptions • They occur for example – When a file we try to open does not exist (FileNotFoundError) – Dividing a number by Zero (ZeroDivisionError) – Module we try to import is not found (ImportError) etc. • Whenever these type of runtime error occur, Python creates an exception object. If not handled properly it prints a traceback to that error along with some details about why that error occurred.
  • 2.
    Exception >>> 1/0 Traceback (mostrecent call last): File "<pyshell#10>", line 1, in <module> 1/0 ZeroDivisionError: division by zero >>> open('i.txt') Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> open('i.txt') FileNotFoundError: [Errno 2] No such file or directory: 'i.txt'
  • 3.
    Built-in Exceptions • Anexception is a value (object) that is raised (“thrown”) signaling that an unexpected or “exceptional” situation has occurred. • Python contains a predefined set of exceptions referred to as Standard Exceptions. Exceptions Description ImportError Raised when an import (or from … import) statement fails IndexError Raised when a sequence index out of range NameError Raised when a local or global name is not found TypeError Raised when an operation or function is applied to an object of inappropriate type ValueError Raised when a built in operation or function is applied to an appropriate type, but of inappropriate value IOError Raised when an input/output operation fails (eg: “file not found”)
  • 4.
    Standard Exceptions • Thestandard exceptions are defined within the exceptions module of the python standard library, which is automatically imported into python programs. • We have seen a number of these exceptions before in our programming. • Raising an exception is a way for a function to inform its client a problem has occurred that the function itself cannot handle. >>> lst[3] Traceback (most recent call last): File "<pyshell#13>", line 1, in <module> lst[3] IndexError: list index out of range >>> lst1[0] Traceback (most recent call last): File "<pyshell#14>", line 1, in <module> lst1[0] NameError: name 'lst1' is not defined >>> int('45') 45 >>> 3+'7' Traceback (most recent call last): File "<pyshell#15>", line 1, in <module> 3+'7' TypeError: unsupported operand type(s) for +: 'int' and 'str‘ >>> int('45.9') Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> int('45.9') ValueError: invalid literal for int() with base 10: '45.9'
  • 5.
    The propagation ofraised exceptions • Raised exceptions are not required to be handled in python. • When an exception is raised and not handled by the client code, it is automatically propagated back to the clients calling code (and its calling code etc) until handled. • If an exception is thrown all the way back to the top level (main module) and not handled, then the program terminates and displays the details of the exception as shown below.
  • 6.
    The propagation ofraised exceptions • If function A calls function B which in turn calls function C and which in turn calls function D and an exception occurs in function D, if it is not handled in D, the exception passes to C and then to B and then to A. • If never handled an error message is split out and program come to a sudden unexcepted halt.
  • 7.
    Exception Handling • CatchingException: – In python, exception can be handled using a try statement. – A critical operation which can raise exception is placed inside the try clause and the code that handles exception is written in except clause. – It is upto us what operations we perform once we have caught the exception. import sys lst = ['x',5,0] for e in lst: try: print("The element is ",e) r = 1 / int(e) print("The reciprocal of ", e," is ",r) except: print("Oops! ", sys.exc_info()[0]," occurred") OUTPUT: The element is x Oops! <class 'ValueError'> occurred The element is 5 The reciprocal of 5 is 0.2 The element is 0 Oops! <class 'ZeroDivisionError'> occurred
  • 8.
    sys.exc_info() • This functionreturns a tuple of three values that give information about the exception that is currently being handled. • The information returned is specific both to the current thread and to the current stack frame. • If the current stack frame is not handling an exception, the information is taken from the calling stack frame or its caller and so in until a stack frame is found that is handling an exception. • Here “handling an exception” is defined as “executing or having executed an except clause”. • If no exception is being handled anywhere on the stack, a tuple containing three None values is returned. • Otherwise, the values returned on (type, value, traceback) – type:- gets the exception type of the exception being handled (a class object) – value:- gets the exception parameter – traceback:- gets a traceback object
  • 9.
    Exception Handling import sys lst= ['x',5,0] for e in lst: try: print("The element is ",e) r = 1 / int(e) print("The reciprocal of ", e," is ",r) except: print("Oops! ", sys.exc_info()," occurred") OUTPUT: The element is x Oops! (<class 'ValueError'>, ValueError("invalid literal for int() with base 10: 'x'"), <traceback object at 0x000001A994DFA4C8>) occurred The element is 5 The reciprocal of 5 is 0.2 The element is 0 Oops! (<class 'ZeroDivisionError'>, ZeroDivisionError('division by zero'), <traceback object at 0x000001A994DFA4C8>) occurred • If no exception occurs, except block is skipped and normal flow continues. • But if any exception occurs it is caught by the except block.
  • 10.
    The try andexcept block • In python, exceptions are handled using the try and except block. • Python, executes the try block as a normal part of the program. • When an error occurs during its exception, the rest of the block is skipped and except block is executed. Example 1: i=1/0 print("i = ",i) print("After division") Traceback (most recent call last): File "C:/Users/swathy/AppData/Local/Programs/Pyt hon/Python37/files1.py", line 1, in <module> i=1/0 ZeroDivisionError: division by zero
  • 11.
    Exception Handling -Example Example 2: try: i=1/0 print("i = ",i) except: print("Some exception occured") print("After division") OUTPUT: Some exception occured After division import sys try: i=1/0 print("i = ",i) except: print(sys.exc_info()[0]," occured.") print("After division") OUTPUT: <class 'ZeroDivisionError'> occured. After division Example 3:
  • 12.
    Exception Handling -Example • Python don’t just handle exceptions if they occur immediately in the try block, but also if they occur inside functions that are called in the try block. import sys def func(): i=1/0 print("Inside function") try: func() print("Inside try block") except: print(sys.exc_info()[0]," occured.") print("After function call inside main module") OUTPUT: <class 'ZeroDivisionError'> occured. After function call inside main module Example 4:
  • 13.
    Catch Multiple Exceptions •We can define as many except blocks as we want to catch and handle specific exceptions. try: print(int('45.6')) except (ZeroDivisionError, ValueError): print("Attempt to divide by zero") except: print("Something else went wrong") OUTPUT: Attempt to divide by zero ZeroDivisionError, ValueError Example 4:
  • 14.
    The Else Clause •The try except block has an optional else clause. • The else clause is executed only if no exceptions are raised Example: try: x = 1/2 print("x = ",x) except: print("Something went wrong") else: print("Nothing went wrong") x = 0.5 Nothing went wrong
  • 15.
    The Finally Clause •The try except block has an optional finally clause. • The finally clause is always executed, whether an exception has occurred or not
  • 16.
    The Finally Clause •We can define as many except blocks as we want to catch and handle specific exceptions. try: x = 1/0 except: print("Something went wrong") finally: print("Always executes this") OUTPUT: Something went wrong Always executes this Example: Example: try: f=open('text1.txt') print(f.read()) except: print("Something went wrong") finally: f.close() OUTPUT: Something went wrong Always executes this
  • 17.
    Raising an Exception •If we want to raise an exception when a certain condition occurs, use raise keyword. • You can define what kind of error to raise, and the text to print to the user. print("Exception handling concepts") raise NameError("An exception occured") Example: x = "hello" if not type(x) is int: raise TypeError("Only integers are allowed") OUTPUT: Traceback (most recent call last): File "keyword_raise.py", line 4, in <module> raise TypeError("Only integers are allowed") TypeError: Only integers are allowed