0% found this document useful (0 votes)
23 views17 pages

Exception Handling

The document discusses exceptions in Python, including syntax errors and runtime exceptions like FileNotFoundError and ZeroDivisionError. It explains how exceptions can be handled using try and except blocks, and introduces concepts such as raising exceptions, the else clause, and the finally clause. Additionally, it covers built-in exceptions and the propagation of raised exceptions through function calls.

Uploaded by

gj88rd466g
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views17 pages

Exception Handling

The document discusses exceptions in Python, including syntax errors and runtime exceptions like FileNotFoundError and ZeroDivisionError. It explains how exceptions can be handled using try and except blocks, and introduces concepts such as raising exceptions, the else clause, and the finally clause. Additionally, it covers built-in exceptions and the propagation of raised exceptions through function calls.

Uploaded by

gj88rd466g
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 17

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] >>> 3+'7'


Traceback (most recent call last): Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module> File "<pyshell#15>", line 1, in <module>
lst[3] 3+'7'
IndexError: list index out of range TypeError: unsupported operand type(s) for +:
'int' and 'str‘
>>> lst1[0]
Traceback (most recent call last): >>> int('45.9')
File "<pyshell#14>", line 1, in <module> Traceback (most recent call last):
lst1[0] File "<pyshell#17>", line 1, in <module>
NameError: name 'lst1' is not defined int('45.9')
ValueError: invalid literal for int() with base 10:
>>> int('45') '45.9'
45
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 OUTPUT:


lst = ['x',5,0]
for e in lst: The element is x
try: Oops! <class 'ValueError'> occurred
print("The element is ",e) The element is 5
r = 1 / int(e) The reciprocal of 5 is 0.2
print("The reciprocal of ", e," is ",r) The element is 0
except: Oops! <class 'ZeroDivisionError'>
print("Oops! ", sys.exc_info()[0]," occurred
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
OUTPUT:
import sys
lst = ['x',5,0] The element is x
for e in lst: Oops! (<class 'ValueError'>,
try: ValueError("invalid literal for int() with
print("The element is ",e) base 10: 'x'"), <traceback object at
r = 1 / int(e) 0x000001A994DFA4C8>) occurred
print("The reciprocal of ", e," is ",r)
except: The element is 5
print("Oops! ", sys.exc_info()," The reciprocal of 5 is 0.2
occurred")
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.
Traceback (most recent call last):
Example 1: File
"C:/Users/swathy/AppData/Local/Programs/Pyth
i=1/0 on/Python37/files1.py", line 1, in <module>
print("i = ",i) i=1/0
print("After division") ZeroDivisionError: division by zero
Exception Handling - Example
Example 2:
try: OUTPUT:
i=1/0
print("i = ",i) Some exception occured
except: After division
print("Some exception occured")
print("After division")

Example 3:
import sys
try: OUTPUT:
i=1/0
print("i = ",i) <class 'ZeroDivisionError'> occured.
except: After division
print(sys.exc_info()[0]," occured.")
print("After division")
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.
Example 4:

import sys OUTPUT:


def func():
i=1/0 <class 'ZeroDivisionError'> occured.
print("Inside function") After function call inside main module

try:
func()
print("Inside try block")
except:
print(sys.exc_info()[0]," occured.")
print("After function call inside main module")
Catch Multiple Exceptions
• We can define as many except blocks as we want to catch and handle
specific exceptions.

Example 4:

try: OUTPUT:
print(int('45.6'))
except (ZeroDivisionError, ValueError): Attempt to divide by zero
print("Attempt to divide by zero")
except: ZeroDivisionError, ValueError
print("Something else went wrong")
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 x = 0.5
print("x = ",x) Nothing went wrong
except:
print("Something went wrong")
else:
print("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.
Example:
try: OUTPUT:
x = 1/0
except: Something went wrong
print("Something went wrong") Always executes this
finally:
print("Always executes this")
Example:
try: OUTPUT:
f=open('text1.txt')
print(f.read()) Something went wrong
except: Always executes this
print("Something went wrong")
finally:
f.close()
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:
OUTPUT:
x = "hello" Traceback (most recent call last):
File "keyword_raise.py", line 4, in
if not type(x) is int: <module>
raise TypeError("Only integers are allowed") raise TypeError("Only integers are
allowed")
TypeError: Only integers are allowed

You might also like