Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 41

Errors and Exception

Handling
• We now consider exception and error handling and
how it is implemented in Python
• The traditional method of handling errors in most of the languages is to
check for return value by a function. The return value will be a positive
integer, representing a true value if the function call works.
• There are few problems with this method of error trapping

• 1. You can only detect success and failure. There is no in between


• 2. You can only really handle the failure. Not the reason for failure

• Python however provides a different method


• When an error occurs within python, an exception is raised.
What is an Exception?
• In Python, everything is a type of object, including integers, strings,
booleans and so are Exceptions and Errors.
• An Exception is a special type of Python object that can be used to
pass information about a failure from the called module to the caller.
• When an exception is raised , it can be trapped and the exception
information is passed to an exception handler
• Unlike C , you can get a precise description of the problem and even
additional information about the error that occurred.
What is an Exception
• Exception/Error types are defined in a class hierarchy with the root of
this hierarchy being BaseException class.
• All built-in errors and exceptions eventually extend from the
BaseException type
• . It has a subclass Exception which is the root of all user defined
exceptions(as well as many built in exceptions)
• In turn ArithmeticException is the base class for all built-in exceptions
associated with arithmetic errors
Python Exception Handling- Class Hierarchy
• When an exception occurs, this is known as raising an
exception

• when it is passed to code to handle this is known as


throwing an exception
• The best way to think about an exception is as a
configurable and expandable signal handler
• You create an exception handler using the try statement
and then execute the statements that you want to
monitor.
• As soon as an exception occurs , control returns to the try
statement
• You do not have to monitor each function call and you
don’t have to rely on simple return values to determine
whether a block of code executed successfully, you just
need to be able to handle an exception if it occurs
What is Exception handling?
• Different types of error produce different types of exception.
• For example, if the error is caused by dividing an integer by zero, then
the exception is a arithmetic exception.
• The type of exception is identified by objects and can be caught and
processed by exception handlers
• Each handler can deal with exceptions associated with its class of
error or exception (and its subclasses).
• An exception is instantiated when it is raised.
• The system searches back up the execution stack (the set of functions or
methods that have been invoked in reverse order) until it finds a handler
which can deal with the exception.
• The associated handler then processes the exception.
• This may involve performing some remedial action or terminating the current
execution in a controlled manner.
• In some cases, it may be possible to restart executing the code.
• As a handler can only deal with an exception of a specified class (or subclass),
an exception may pass through a number of handler blocks before it finds one
that can process it
What happens when an exception occurs
• When an exception occurs, the default operation is for the python
interpreter to identify the error and then produce a stack trace of
how the error occurred and how you got there
• This is more useful than the typical error output produced by Perl or
C, where you normally see the line where the error occurred
• This can make tracing the reason for the error very difficult
• The above figure illustrates a situation in which a divide by zero exception called ZeroDivisionError is
raised.
• This exception is passed up the execution stack where it encounters an exception handler defined for an
End of File exception.
• This handler cannot handle the ZeroDivisionError and so it is passed further up the execution stack.
• It then encounters a handler for an out of memory exception.
• Again, it cannot deal with a ZeroDivisionError and the exception is passed further up the execution stack
until it finds a handler defined for the ZeroDivisionError.

• This handler then processes the exception


Handling an Exception
• You can catch an exception by implementing the try—except construct.
• This construct is broken into three parts:
1. try block.
The try block indicates the code which is to be monitored for the exceptions listed in the except
expressions.
2. except clause.
You can use an optional except clause to indicate what to do when certain classes of exception/error occur
(e.g. resolve the problem or generate a warning message). There can be any number of except clauses in
sequence checking for different types of error/exceptions.
3. else clause.
This is an optional clause which will be run if and only if no exception was thrown in the try
block. It is useful for code that must be executed if the try clause does not raise an exception.
• 4. finally clause. The optional finally clause runs after the try block exits (whether or not this is due to
an exception being raised).You can use it to clean up any resources, close files, etc.
Example

• We can handle this by wrapping the call to runcalc within a try statement and providing an except clause.

• The syntax for a try statement with an except clause is:


• A concrete example of this is given below for a try statement that will be used to monitor a call to runcalc:
• which now results in the string 'oops' being printed out.

• This is because when runcalc is called the '/' operator


throws the ZeroDivisionError which is passed back to the
calling code which has an except clause specifying this type
of exception.
• This catches the exception and runs the associated code
block which in this case prints out the string 'oops '.
• In this case the first except monitors for a ZeroDivisionError but the
other excepts monitor for other types of exception.
• Note that the except Exception is the last except clause in the list as
ZeroDivisionError, IndexError and FileNotFoundError are all
eventual subclasses of Exception and thus this clause would catch
any of these types of exception.
• As only one except clause is allowed to run; if this except handler
came list the other except handers would never ever be run.
• The important thing to remember is to work from
the most specific exception to the least specific
exception. If you would have placed EXCEPTION –
the base class for all exception types- in the first
except statement, the remaining handlers would
never have got checked
• The try…finally statement is useful in those situations where you want to
run a piece of code, irrespective of whether an exception occurs

• For example , when communicating with a remote server over a


network , you want to trap error but still make sure that regardless of the
error, the communication channel is closed
• With a try…finally statement you can do it
• try:
• remote.send_data(destination,datastream)
• finally:
• remote.close_connection()
• On its own, a try…finally statement will only propogate the error upto the
next level, so you will probably want to embed the call within another try
statement

• try:
• try:
• remote.send_data(destination,datastream)
• finally:
• remote.close_connection()
• except NetworkError,errorstr:
• Print(“error: couldnot send the data:”, errorstr)
else:
print(“data sent successfully”)
• Now the connection is closed whether or not an
exception occurs, while the outer try statement traps
and handles the actual exception raised during the
process
Exceptions Nest
• So exceptions are always handled by the enclosing exception handler
• But what happens if your exception handler doesn’t explicitly handle
every possible exception?

• The answer is quite simple: the exception is raised to the next higher
level exception
Built in Exceptions
• Python comes with a number of base exceptions and exception
classes.
• All of these exceptions can be used and trapped within your scripts to
indicate or identify an error
Exception
• This is the root class used for all exceptions
StandardError
• StandardError is the base class used for all the
built-in exceptions. StandardError inherits the
facilities offered by the Exception root class
ArithmeticError
• For exceptions arising due to arithmetic errors, one of the
specific arithmetic exceptions (OverFlowError,
ZeroDivisionError, FloatingPointError) is raised .
ArithmetiticError is the base class used by all the three
exceptions to indicate a general arithmetic fault.
• Since it is base class , you can use this exception to trap all
the the three arithmetic errors
AssertionError
• AssertionError is the exception raised when an assert statement fails
AttributeError
• AttributeError is the exception raised when an attribute
reference or assignment fails
EnvironmentError
• EnvironmentError is the class for errors that occur outside of Pythons
control, that can be traced to the environment in which Python is
operating
EOFError
• EOFError is the exception raised when the endof file condition is
detected by the built in data handling functions
FloatingPointError
• The FloatingPointError exception is raised when a floating point
operation fails
ImportError
• The importError exception is raised when an import statement fails to
find the specified module or when from fails to find the specific
symbol in the module
IndexError
• The IndexError exception is raised when you try to access a sequence
element out of the range of sequences size
IOError
• The IOError exception is raised when an I/O operation fails, for
example trying to open a nonexistant file or trying to write to a device
with no free space
KeyError
• The keyError exception is raised when the dictionary or other
mapping key requested does not exist within the mapping object
LookupError
• LookupError is the base exception class for the built –in IndexError
and KeyError exceptions. This exception is used to indicate an error
when accessing information from a sequence (string,list or tuple) or
mapping (dictionary)
MemoryError
• The MemoryError exception is raised when the interpreter runs out of
memory while executing a specific option , but still thinks it can
recover from the situstion if some objects are deleted to free up
memory space.
Other Built-in exceptions
• KeyboardInterupt SystemError
• NameError SystemExit
• NotImplementedError TypeError
• OSError UnboundLocalError
• OverflowError UnicodeError
• RuntimeError
• SyntaxError
• In Python the terms Error and Exception are used inter-
changeably;

• Exceptions are commonly used to represent issues with


operations such as arithmetic exceptions

• errors are associated with functional issues such as a file not


being found

You might also like