Exception Handling in Python
Python
Exceptions
Exception Handling
Try and Except
Nested try Block
Handling Multiple Exceptions in single Except Block
Raising Exception
Finally Block
User Defined Exceptions
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 or parsing error
⚫ 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)
⚫ 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 Handling
⚫To handle exceptions, and to call code
when an exception occurs, we can use a
try/except statement.
⚫The try block contains code that might
throw an exception.
⚫If that exception occurs, the code in the
try block stops being executed, and the
code in the except block is executed.
⚫If no error occurs, the code in the except
block doesn't execute.
TypeError
ValueError
NameError
ImportError
IndexError
KeyError
Nested Try
Block
Nested Try
Block
Nested Try Block
⚫Multiple except blocks
⚫A try statement can have
multiple different except blocks
to handle different exceptions.
⚫Multiple exceptions in a single
except block
⚫Multiple exceptions can also be put into a
single except block using parentheses, to
have the except block handle all of
them.
Raising Exceptions
Raising Exception
⚫Raising exception is similar to
throwing exception in C++/Java.
⚫You can raise exceptions by
using the raise statement
User Defined Exception
finally
⚫To ensure some code runs no matter
what errors occur, you can use a
finally statement.
⚫The finally statement is placed at the
bottom of a try/except statement.
⚫Code within a finally statement
always runs after execution of the
code in the try, and possibly in the
except, blocks.
⚫Code in a finally statement even runs
if an uncaught exception occurs in one
of the preceding blocks.
USER DEFINED EXCEPTIONS
USER DEFINED EXCEPTIONS
USER DEFINED EXCEPTIONS
USER DEFINED EXCEPTIONS
PROGRAM TO COUNT THE TOTAL NUMBER OF WORDS IN
A FILE
PROGRAM TO COPY THE CONTENT OF ONE FILE INTO
ANOTHER
f=open("swap.py","r")
f1=open("birds.py","w")
s=f.read()
print(s)
for i in s:
f1.write(i)
MODULES
MODULES
MODULES
MODULES
MODULES
PACKAGES
PACKAGES
PACKAGES
PACKAGES
PACKAGES
PACKAGES
PACKAGES
PACKAGES

exception handling.pptx