python exception

By | March 12, 2019

Python Exception-: An exception is an object generated automatically by Python functions with a raise statement. After the object is generated the raise statement which raises an exception, causes execution of the Python program to proceed in a manner different from what would normally occur.

Instead of proceeding with the next statement after the raise or whatever generated the exception  the current call chain is searched for a handler that can handle the generated exception. If such a handler is found it is  invoked and may access the exception object for more information. If no suitable exception handler is found, the program aborts with an error message.

Types of Python exceptions-: It is  possible to generate different types of exceptions to reflect the actual cause of the error or exceptional circumstance being reported. Python 3.6 provides several exception types

BaseException
    SystemExit
    KeyboardInterrupt
    GeneratorExit
    Exception
        StopIteration
        ArithmeticError
            FloatingPointError
            OverflowError
           ZeroDivisionError
        AssertionError
        AttributeError
        BufferError
        EOFError
        ImportError
            ModuleNoteFoundError
        LookupError
            IndexError
            KeyError
        MemoryError
        NameError
            UnboundLocalError
        OSError
            BlockingIOError
            ChildProcessError
            ConnectionError
                BrokenPipeError
                ConnectionAbortedError
                ConnectionRefusedError
                ConnectionResetError
            FileExistsError
            FileNotFoundError
            InterruptedError
            IsADirectoryError
            NotADirectoryError
            PermissionError
            ProcessLookupError
            TimeoutError
        ReferenceError
        RuntimeError
            NotImplementedError
            RecursionError
        SyntaxError
            IndentationError
                TabError
        SystemError
        TypeError
        ValueError
            UnicodeError
                UnicodeDecodeError
                UnicodeEncodeError
                UnicodeTranslateError
        Warning
            DeprecationWarning
            PendingDeprecationWarning
            RuntimeWarning
            SyntaxWarning
            UserWarning
            FutureWarning
            ImportWarning
            UnicodeWarning
            BytesWarningException
            ResourceWarning

Each type of exception is a Python class which inherits from its parent exception type.

Raising exceptions-: Exceptions are raised by many of the Python built-in functions:

>> alist = [1, 2, 3]
>>> element = alist[7]
Traceback (innermost last):
File "<stdin>", line 1, in ?
IndexError: list index out of range

Error-checking code built into Python detects that the second input line requests an element at a list index that does not exist and raises an IndexError exception. This exception propagates all the way back to the top level  which handles it by printing out a message stating that the exception has occurred.

Exceptions may also be raised explicitly in our own code through the use of the raise statement. The most basic form of this statement is

raise exception(args)

The exception(args) part of the code creates an exception. The arguments to the new exception are typically values that aid we determining what happened something that . After the exception has been created raise throws it upward along the stack of Python functions that were invoked in getting to the line containing the raise statement. The new exception is thrown up to the nearest  exception catcher looking for that type of exception. If no catcher is found on the way to the top level of the program the program terminates with an error or (in an interactive session) causes an error message to be printed to the console.

Catching and handling exceptions-: The important thing about exceptions are not  that they cause a program to halt with an error message. Achieving that function in a program is never much of a problem. A special about exceptions is that they don’t have to cause the program to halt. By defining appropriate exception handlers we can ensure that commonly encountered exceptional circumstances do not cause the program to fail. perhaps they display an error message to the user or do something else perhaps even fix the problem, but they do not crash the program.

The basic Python syntax for exception catching and handling is as follows, using the try, except, and sometimes else keywords as like

try:
    body
except exception_type1 as var1:
    exception_code1
except exception_type2 as var2:
    exception_code2
    .
    .
    .
except:
    default_exception_code
else:
    else_body
finally:
    finally_body

A try statement is executed by first executing the code in the body part of the statement. If this execution is successful body is executed, and the try statement is finished. Because there is a finally statement, finally_body is executed. If an exception is thrown to the try, the except clauses are searched sequentially for one whose associated exception type matches that which was thrown.

If a matching except clause is found the thrown exception is assigned to the variable named after the associated exception type and the exception code body associated with the matching exception is executed.

If the line except exception_type as var matches some thrown exception exc, the variable var is created and exc is assigned as the value of var before the exception-handling code of the except statement is executed. we don’t need to put in var, we can say something like except exception_type:, which still catches exceptions of the given type but doesn’t assign them to any variable.

Defining new exceptions-: We can easily define new exception. as like

class MyError(Exception):
    pass

Debugging programs with the assert statement-: The assert statement is a specialized form of the raise statement:

assert expression, argument

The AssertionError exception with the optional argument is raised if the expression evaluates to False and the system variable __debug__ is True.

The exception inheritance hierarchy-:  Python exceptions are hierarchically structured and on what that structure means in terms of how except clauses catch exceptions.

The following code

try:
body
except LookupError as error:
exception code
except IndexError as error:
exception code

catches has two types of exceptions:

  • IndexError
  • LookupError.

It just so happens that IndexError is a subclass of LookupError. If body throws an IndexError that error is first examined by the except LookupError as error line and because an IndexError is a LookupError by inheritance, the first except succeeds. The second except clause is never used because it is  subsumed by the first except clause.

In  flipping the order of the two except clauses could potentially be useful, then the first clause would handle IndexError exceptions, and the second clause would handle any LookupError exceptions that are not IndexError errors.

Use of exception-:  Exceptions are natural choices for handling almost any error condition. It is  an unfortunate fact that error handling is often added when the rest of the program is largely complete but exceptions are particularly good at intelligibly managing this sort of after-the-fact error-handling code (or, more optimistically, when we are adding more error handling after the fact).

Exceptions are also highly useful in circumstances where a large amount of processing may need to be discarded after it becomes obvious that a computational branch in our program has become untenable. The spreadsheet example is one such case others are branch-and-bound algorithms and parsing algorithms.

Example of python exception ..

try:
  print(a)
except NameError:
  print("Variable a is not defined")
except:
  print("Something else went wrong")

Output of this programe

Variable a is not defined

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *