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.
NESTED TRY BLOCK
⚫A try statement can have
multiple different except
blocks to handle different
exceptions.
⚫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 FROM
EXCEPT BLOCK
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 EXCEPTION