You are on page 1of 8

Programming using Python

prutor.ai Amey Karkare


Dept. of CSE
IIT Kanpur

For any queries reach out to rahulgr@iitk.ac.in or rahulgarg@robustresults.com


or whatsapp 9910043510

1
Python Programming
Programming with Python

prutor.ai
Exceptions

2
Programming
Exceptions

prutor.ai

Programming
Exceptions
• Exceptions are Pythons's way of telling user
that something unexpected has happened

prutor.ai
• Most often an indication of some failure
– Access violation (writing to a read-only file)
– Missing resource (reading a non-existent file)
– Type incompatibility (multiplying two strings)
– Bound violation (accessing a string beyond limit)
• We have seen exceptions in our example

Programming
Exceptions

prutor.ai
Exception when reading a closed file

Programming
Exceptions can be Handled
• To recover from unexpected operation
• try:
try ... except ... else ...

prutor.ai
Operations that can raise exceptions.
except [Optional list of exceptions] :
In case of exceptions, do the recovery.
else: # else is optional
If no exception then do normal things.

• try
try:
... finally ...
Operations that can raise exceptions.
finally:
Execute irrespective of whether exception
was raised or not. Typically clean-up stuff.
6

Programming
Example

(
prutor.ai )

( )

Programming
More about try…except
• A try statement may have more than one
except clause

prutor.ai
▪ to specify handlers for different exceptions.
• At most one handler will be executed.
• An except clause may name multiple
exceptions as a parenthesized tuple.
• The last except clause may omit the exception
name
– Catches any exception
8

Programming

You might also like