Exception Handling

Exceptions

Python code doesn’t work always as we want and therefore raises errors and exceptions. Errors are more common to happen due to syntax like missing parenthesis or indentation. Exceptions happen when something really goes wrong with the execution of the code, like iterating over a list and going out-of-bounds of the list size or trying to access a not existing file.

 

>>> 10 * (1/0)
Traceback (most recent call last):
  File "", line 1, in
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "", line 1, in
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "", line 1, in
TypeError: Can't convert 'int' object to str implicitly

 

Exception Handling

It is possible to write programs that handle specific exceptions letting the user control how the program will respond to an exception; note that a user-generated interruption is signaled by raising the KeyboardInterrupt exception.

 

while True:
     try:
         x = int(input("Please enter a number: "))
         break
     except ValueError:
         print("Oops!  That was no valid number.  Try again...")

 

Output:

Please enter a number: 2


The example above tries to ask for an input that is a number and keeps on trying in a while loop until it works out well. If the user inputs anything other than a number an exception will be raised “catching” it. This is a way to avoid the program to crash telling it “Okay, try to do this but lookout that it might happen this (whatever exception is being caught in the except field), and if it happens then do this (which in this case is printing a message)”.


Exception – Try Clause

• try clause (whatever is between the try and the first except) is executed.
• If no exception occurs, the except clause is skipped and execution of the try statement is finished.
• If an exception occurs during the execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.
• If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a default message.


User-defined Exceptions

Programs may name their own exceptions by creating a new exception class. 
Exceptions should typically be derived from the Exception class. Exception classes can be defined which do anything any other class can do, but are usually kept simple.

 

class Error(Exception):
    """Base class for exceptions in this module."""
    pass
class InputError(Error):
    def __init__(self, expression, message):
        self.expression = expression
        self.message = message
class TransitionError(Error):
    def __init__(self, previous, next, message):
        self.previous = previous
        self.next = next
        self.message = message

 

For a list of all built-in exceptions that Python supports by default, refer the link: https://docs.python.org/3/library/exceptions.html

 

Related Tutorials