Introduction to Exception Handling in Python by MarsDevs.
This article will present to you what Exceptions are, why they are needed, how exceptions can be raised manually, and how to handle exceptions.
Introduction to Exception
When we try to execute the code, errors might occur. These errors interrupt the normal flow of the program. The Python interpreter often fails to deal with these errors and raises an exception.
Error handling is needed to prevent a program from ending abruptly. Exceptions are raised whenever an error occurs in the program. Exceptions can be defined as errors found during execution.?
If exceptions are not handled, the program may go into a crash state. As developers, we are responsible for handling exceptions that occur such that the program will execute in any case.
Consider the following example,
There is an unhandled exception in the above code.
Exceptions can be referred to as unexpected behavior of an application or program. It is also known as some interruption in the flow of code. Whatever it is, it is the developer's duty to handle all these exceptions. Python, like other programming languages, is equipped with provisions for handling exceptions. One way is to use try and except blocks.
The try block allows us to write the code which is likely to have errors or exceptions. If any exception occurs then the except block is triggered. In except block, developers can control the flow of the program. Thus, helped in handling the exceptions.?
You can write any important code inside the try block. The exception block is triggered whenever an expected or unexpected exception occurs (except the clause can detect any number of exceptions raised inside the try clause).
In order to get a clear understanding of try & except, let’s consider an example.
The Python interpreter raises an exception as an object that contains information about the exception message and type. Furthermore, every exception type in Python inherits from the base class Exception.
Consider the following example,
Now, let us discuss some common exceptions in Python. Furthermore, all built-in exceptions in Python are inherited from the Exception class.
Name of the Exceptions?
To check all exceptions, visit?python’s official documentation on exceptions .
Consider the following examples,
As discussed earlier, whenever an exception is raised in the try block, the exception clause will handle it. But it is a good practice to handle or catch all specific types of exceptions, for this, we can use multiple except blocks.
Consider the following example,
领英推荐
In the above example, we have handled 2 exceptions (using 2 except blocks) based on the input entered by the user. If q is not zero, the output will be 1. If q is 0, the output will be 2. If we want to catch both the exceptions in one except block then the code can be rewritten as
Raising Custom Exceptions
Although exceptions are automatically raised during runtime when an error occurs, we can also create custom exceptions using the raise keyword. Any exception that a developer can raise if he needs to break the flow of a program under specific circumstances can be called a custom exception.
Consider the following example,
But, if you pass a string by the first name, it will print accordingly.
Use of Try - Except - Else
Sometimes we need to run the program only when there is no exception, in that case, the else keyword is used with the try clause.
If an exception is raised then the except block will be triggered, otherwise, the else block will be triggered.
Consider the following example,
In the above example, since the value of num2 is greater than 0, no ZeroDivisionError is raised and hence the flow of code moves to the else block and the message is no exception.
Consider another example,
In this example, since num2 is 0, the flow of code goes through the except block and we get the message exception.
Try clause with Finally
The finally keyword is used when we want a piece of code to be executed, regardless of whether exceptions are raised or not. The finally keyword comes after the try-except or else block.
Consider the following example,
In the example above, we try to access the fifth element of the list, so in addition to handling this error and giving the list index out-of-bounds exception, the code in the finally block is printed despite the exception.
Consider another example,
Note that the else block will always be triggered when there is no exception raised and the finally block will always be triggered regardless of any exceptions or not.