Python Basic – How to Handle the Exceptions & Errors in Python

Table of Contents

Related Tutorials

Exceptions or Error Handling

Error handling is an important part of any programming language, including Python. It helps to detect and handle runtime errors so that the program can continue executing even when something goes wrong. This makes the program more robust and less prone to crashing.

In Python, errors can be handled using exceptions. An exception is an error that occurs during the execution of a program. When an exception is raised, the normal flow of the program is disrupted and the program execution stops. Python provides several built-in exceptions, such as ZeroDivisionError, ValueError, and TypeError, that can be raised by the Python interpreter in response to runtime errors.

Exceptions can be handled using the “try…except” statement. The try block contains the code that might raise an exception, and the except block contains the code that should be executed when an exception is raised.

Exceptions in Python

This is an event that occurs when there is an interruption in the normal execution of a program. That is, when a Python script encounters a problem that it cannot avoid or solve, then the execution of the program is stopped – such an event is called an exception. The lexical meaning of exception also implies the origin of an exceptional condition.

Exceptions are usually made to the program for incorrect code or input which, if not handled properly, can cause the program to shut down unexpectedly. Let us try to understand with an example –


   P = 38
   Q = 0
   print("Hello EnableGeek!")


   Traceback(most recent call last):
       line 180, in <module >
   ZeroDivisionError: division by zero

In the above program, according to the rules of mathematics, it is not possible to divide P by Q and so whenever the print (P/Q) statement wants to be executed, a kind of exception condition arises which is called an exception. And so Python did not execute the subsequent statements of that program but stopped executing the program. But it turns out that there is nothing wrong with the code or the rules. This situation is created only at run time. So Python makes exceptions in such cases.

Different exceptions are made in the program for different reasons. Python has many exceptions to the rule of thumb for certain reasons. Here are some of them:

Name of ExceptionsDescriptions
ExceptionBase class of all kinds of exceptions
RuntimeErrorWhen an exception occurs that does not fall within the specific category of Python exceptions
StopIterationWhen the next() method of an iterator does not point to an object
When an index is not found in a sequence-type object according to the demand
ArithmeticErrorBase class of exceptions made for numerical calculations
OverflowErrorWhen a numeric type exceeds the maximum limit
ZeroDivisonErrorWhen dividing by zero occurs
ImportErrorWhen the import statement fails, that is, the import is not completed for any reason
NameErrorWhen no identifier with a specific name can be found within the local or global scope
IOErrorWhen no operation related to input or output is successful such as an open function for reading from the file cannot work
SyntaxErrorIndentationErrorIf there are any keywords or statements that are incorrect when writing Python programs

Exception handling

As we saw in the previous chapter, the program closes unexpectedly when an exception is made. The good news is that if you can handle such exceptions properly, the program will continue to move forward without stopping, and you will be able to easily identify any problems with the program. For this Python has try, except for the use of statements.

The code is written in the try block where the exception can be created (for user input or other such reasons). And except for the code written in the block which will be executed if any attempt is actually made in that try block. In other words, if the exception is created in try, the code execution of this block will be stopped, but the code of the block will be executed normally. Let’s look at an example –


       P = 555
       Q = int(input("Enter a divisor to divide 555: "))
   except ZeroDivisionError:
       print("You entered 0 which is not permitted!")

If the input is as follows, Then the Output:

   Enter a divisor to divide 555: 5
   Enter a divisor to divide 555: 15
   Enter a divisor to divide 555: 10

If the input is as follows, But the Output:

   Enter a divisor to divide 555: 0
   You entered 0 which is not permitted!

The above program has been divided into two numbers. The value of one number is 555 and I am taking another from the user. If the user gives the correct number of inputs well (e.g. 5) then the program is working correctly and printing the quotient. But we do not know the attitude of the user. The user can give 0 as input if he wants. And then the program will close unexpectedly without being able to execute.

And so by guessing we have written the code in a Try block and if an exception is created due to division in that block then we have used the exception block to handle it and specifically handle the ZeroDivisionError exception. Now, the user can give zero input if he wants, so the program will not shut down or shut down unexpectedly. Instead, the user is able to continue the normal work by showing the appropriate message.


       store = 10
       print(store + "EnableGeek")
       print(store / 2)
   except ZeroDivisionError:
       print("Divided by zero")
   except (ValueError, TypeError):
       print("Type or value error occurred")


   Type or value error occurred

In the above program, two types of error can occur in the try block. The variable could have been divided by zero instead of 2 and in that case, a ZeroDivisionError exception would have been created. Again, the second statement of the try-block is where an attempt has been made to print by adding a string with an integer. This is where the exception is being made. And so the TypeError exception is being created. But we handled it correctly and so the program did not rush to shut down but executed a print statement print(“Type or value error occurred”) that we had determined.

If you want, except blocks can be used without defining any exceptions in a specific way. In that case, this except block will run for any exceptions that occur within the try block. Such as –


       value = "data"
       print(value / 0)
       print("An error occurred")


   An error occurred

This means that the code to share the data of the opposite type has been written in the try block. Exceptions are certainly being made here at run time. And so the error handle has also been made using except blocks. Although the matter may seem good at first glance, the exact cause of the mishap in the tri-block cannot be identified by the block handled in this way.

Share The Tutorial With Your Friends