As in all the other languages, python also provides exception and error handling with its several features or methods. We can easily say that exception handling is pretty much different in Python compared to other languages as there are much more exception handling ways or keywords in Python as compared to other languages. So let’s dive into it.
Catching Exceptions (try-except) in Python
We will first see about incorporating exception handling in Python and later on we will also take an example to clearly understand about the same.
- Exceptions can be detected by incorporating them as part of a try statement.
- There are two main forms of the try statement: try-except and try-finally.
- A try statement can be accompanied by one or more except clauses, exactly one finally clause, or a hybrid try-except-finally combination.
- try-except statements allow one to detect and handle exceptions.
- There is even an optional else clause for situations where code needs to run only when no exceptions are detected.
Following is the syntax when you handle exception using try-except block of Python:
Well, now let’s take a sample code which we will put inside the above given syntax. This will clarify implementation of the try-except clause.
The above given code handles ‘IOError‘ and will display the error message ‘e‘. We can also see that the scope management i.e. beginning and ending of scope for try and except is completely same as we did in defining and working with functions in Python. Which means that a ‘:’ starts the scope and runs on until you keep on coding with a tab and as soon as you untab the code the scope ends.
We can also have multiple excepts with a single try as shown in the syntax below:
We now take an example, which will have syntax filled up with code.
The code in the above example handles to types of error i.e. TypeError as well as ValueError.
Built-in Exceptions in Python
Following is the list of some built-in exceptions with error messages:
|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.|
|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.|
|IndentationError||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 sys.exit() function.|
|TypeError||Raised when a function or operation is applied to an object of incorrect type.|
|UnboundLocalError||Raised when a reference is made to a local variable in a function or method, but no 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.|
We can also define our own exception in Python (if required). We’ll see about it later on.
We saw multiple excepts with single try wherein every except statement was handling a specific exception. Now, in Python, similar to other languages we can also have more than one exceptions handled by a single except statement as shown in the example below:
Here you can see that all the three types of errors are handled by a single except statement.
finally in Exception Handling
It works in pretty much similar way as it does in other programming languages. In a simple way, the code or logic kept inside the finally statement is going to work irrespective of whether exception is caught or not. Following is its example:
When you run this code, note that the print statement inside finally always works and always prints the text inside it. It is not at all dependent on whether exception is caught or not. Thus, we use finally when we want to display a specific message or want to perform a specific operation every time when the user exits the program or application.
Till now, whatever we saw in exception handling was similar to the exception handling features in other languages. Only there is difference in some syntax and keywords as well as scoping. Let us now see the features of exception handling that sets Python apart from other languages.
else in Exception Handling
- We have seen the else statement with other Python constructs such as conditionals and loops.
- With respect to try-except statements, its functionality is not that much different from anything else you have seen: The else clause executes if no exceptions were detected in the preceding try suite.
The example below shows its working:
So from this example, we can say that the else only executes if there are no exceptions. This makes it very special and a feature of exception handling in Python. As we saw earlier, we’ve also got finally, but the drawback of finally is that it always executes no matter whether there is an exception or not. Also, you can use else along with finally as shown in the example below:
Following is the output of the above given example:
Hence, we can say that else along with finally gives us a luxury of deciding what to do if the exception is caught and what not to do if the exception is not caught. else introduces conditional exception handling in Python which is very much unlike other programming languages.
Sometimes we also require to throw an exception or error purposely in order to satisfy some specific application requirements. In this case, the developer needs to explicitly generate an exception. so now we see that how can we do that ?
raise in Exception Handling
- Python provides a mechanism for the programmer to explicitly generate an exception as it may be required sometimes as described above: this mechanism is the raise statement.
- The raise statement is quite flexible with the arguments it supports, translating to a large number of different formats supported syntactically.
Following is its syntax:
- SomeException, is the name of the exception to raise.
- The second expression contains optional args (aka parameters, values) for the exception.
- The final argument, traceback, is also optional (and rarely used in practice), and, if present, is the traceback object used for the exception normally a traceback object is newly created when an exception is raised.
Let us take an example of raise:
Following is the output of the above given example. We can see that it directly prints out the error statement of raise statement.
Thus, in the raise statement we can generate an error explicitly as and when required but what in the case when we want to generate an explicit error only if a specific condition takes place in the system. For example, let us say that I am building a water tank, and I want it to be filled by the user with a specific rate of water only as it the user exceeds that rate then the tank might broke apart, thus, if the user exceeds that specific rate then an explicit error should be generated so that systems breaks through and filling of water is stopped.
Hence, in the above scenario, we would like to generate raise only if a specific condition of rate of filling is met. In other programming languages, this given scenario would be very difficult to execute and would require a very complex logic to be implemented which results in so many lines of code and it eventually becomes very time consuming.
In order to handle catastrophic conditions, such as described in the scenario above, Python has got a very good functionality, which is easy to implement and understand. So what’s this ? We see it now.
assert in Exception Handling
- The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more accurate, a raise-if-not statement). This is what we require as mentioned in the scenario above.
- An expression is tested, and if the result comes up false, an exception is raised.
- Assertions are carried out by the assert statement.
- The assert statement evaluates a Python expression, taking no action if the assertion succeeds, but otherwise raising an AssertionError exception.
Here is its syntax:
Let us see some examples of assertions, which are true, that is they will not generate any kind of error. We will also see the ones which generates the exceptions.
Just as shown in the example above, assert statements are always of single line and can be kept at an important point of code or logic where checking of a specific variable against some value is very much necessary as not checking of it may lead to some catastrophic event which results in the failure of the whole system. In this example as mentioned all the assertions are true and hence no exception is generated.
Now we take an example below, where assertion fails and we will be above to see the AssertionError generated.
We saw the exception generated in the example. Now, it is also worth noticing that AssertionError exceptions can be caught and handled like any other exception using the try-except statement. Although, we never do so as AssertionError is meant to be generated and not caught.
So, I guess that’s everything about Exception Handling in Python. In next post, we will have a glimpse into how can we do Object Oriented Programming in Python.