PYTHON EXCEPTION HANDLING
EXCEPTIONS
• An exception is an error which occurs during run time of a program.
• Python is capable of handling exceptions thus determining what
particular part of the program encountered a problem
• Typically your program will instantly crash/close if an error is
encountered during the run time of a program, this happens because of
an unhandled [Link], it is very important to handle exceptions
to avoid unnecessary crashes in the program.
TYPES OF EXCEPTIONS
There are several types of exceptions which can be handled by python.
Exception Cause of Error
AssertionError Raised when assert statement fails.
AttributeError Raised when attribute assignment or reference fails.
EOFError Raised when the input() functions hits end-of-file condition.
FloatingPointError Raised when a floating point operation fails.
GeneratorExit Raise when a generator's close() method is called.
ImportError Raised when the imported module is not found.
IndexError Raised when index of a sequence is out of range.
KeyError Raised when a key is not found in a dictionary.
TYPES OF EXCEPTIONS
KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or delete).
MemoryError Raised when an operation runs out of memory.
NameError Raised when a variable is not found in local or global scope.
NotImplementedError Raised by abstract methods.
OSError Raised when system operation causes system related error.
OverflowError Raised when result of an arithmetic operation is too large to be represented.
ReferenceError Raised when a weak reference proxy is used to access a garbage collected referent.
RuntimeError Raised when an error does not fall under any other category.
StopIteration Raised by next() function to indicate that there is no further item to be returned by iterator.
SyntaxError Raised by parser when syntax error is encountered.
IndentionError Raised when there is incorrect indentation.
TabError Raised when indentation consists of inconsistent tabs and spaces.
SystemError Raised when interpreter detects internal error.
SystemExit Raised by [Link]() function.
TypeError Raised when a function or operation is applied to an object of incorrect type.
Raised when a reference is made to a local variable in a function or method, but no
UnboundLocalError
value has been bound to that variable.
UnicodeError Raised when a Unicode-related encoding or decoding error occurs.
UnicodeEncodeError Raised when a Unicode-related error occurs during encoding.
UnicodeDecodeError Raised when a Unicode-related error occurs during decoding.
UnicodeTranslateError Raised when a Unicode-related error occurs during translating.
ValueError Raised when a function gets argument of correct type but improper value.
ZeroDivisionError Raised when second operand of division or modulo operation is zero
GENERATING THE EXCEPTION ERROR PROMPT
An exception can be modified in order to show how an exception works
Syntax:
except ImportError:
print(“Problem encountered from import”)
• Through this you can customize the message which will be displayed if
the exception is encountered in your program.
HANDLING EXCEPTIONS
In handling exceptions the best approach is to implement a try-except block
which allows you to catch possible exceptions during runtime.
• This code works by executing the
Syntax: task within try:, if a problem or an
exception occurs, instead of
try: crashing the except clause will
#Do Something here execute the print error message.
except [name_of_exception] :
print(“Message for the error goes here”) • The name of the exception should
be specified else it will catch all
possible exceptions.
OTHER HANDLING APPROACHES
Syntax: • This approach works very similar
with the initial handling approach
try: however, an else clause is used.
#Do Something here
except [name_of_exception] : • The else command will be
print(“Message for the error goes here”) executed if the try didn’t
else: encounter any problem. Thus,
#Other task to execute skipping the except clause.
OTHER HANDLING APPROACH
Syntax: • This approach works very similar
with the initial handling approach
try: however, a finally clause is used.
#Do Something here
except [name_of_exception] : • The finally clause will be executed
print(“Message for the error goes here”) regardless if the try encountered
finally: no problem or even if it does the
#last task to execute finally clause will still be executed.
• Very useful for tasks required to
be done even if errors are
encountered.
RAISING AN EXCEPTION
An exception can be forced if necessary through the use of raise [Link]
allows the developer to execute an exception task or catch a possible error.
Syntax:
• Raising an exception will instantly
try: move the pointer to the except
raise NameError(‘xxx’) clause. Thus, forcing the try to
except NameError: stop and automatically execute
print(“An error will be forced”) the exception created.