Python Exception Handling

Python Exception Handling

posted 9 min read

While working on the Python code you come across a situation where your program is stopped by the compiler during the execution and something like an error is displayed on the terminal, exception handling was the solution at that time. Well, that is a common problem in every developer's life. In this tutorial I will talk about Python exceptions and different types of exceptions with examples, also why exception handling is important, and how Python manages these exceptions effectively. Let's get started.

Why Error Handling Matters?

Suppose you are using a food ordering application and suddenly the app crashes. You have no idea why the app stopped working. So, exception handling is essential as it prevents the app from future errors and handles them effectively. Exception handling helps you with the smooth execution of your programs and removes the risk of abnormal event occurrence if it's handled during the program development phase. If some errors are left unchecked then that will cause the application to crash, data loss, and worse, so that is the reason exception handling is a significant matter.

  1. It prevents the software from crashing and stopping abruptly.
  2. Make the user experience better by reducing the frustration and confusion with properly displaying the error message.
  3. It ensures data safety and integrity and handles data reliability.
  4. It also helps the developer to safeguard their application from hacker attacks.
  5. It reduces the need for future cost increments for technical support and saves time beforehand.

How Python Manages Errors with Exception Handling?

During your programming life, you may encounter many types of errors, which can be a syntactical error, an error that comes upon run-time, or a logical error. We can resolve the syntax error simply because it will show the error on the compilation time run time error occurs it will not halt the program compilation but shows unexpected behavior during the execution time that deviates from the normal flow of the program.

Note: Remember, a syntax error is a common error that can be caught before execution but if it is not caught in some situation at compile time then there is one built-in exception as well.

Exception Handling Different Ways

Python manages the errors by writing the program that handles the exception. There are many ways for exception handling in Python. So, let's dive into it:

  • Try: When you see that a specific piece of code will cause the error, you put it inside the try block.
  • Except: If the code in the try block creates an error. Python will jump to the except block and execute it. So, right after the try block, we must write the except block.
  • Finally: After using the try and except block, you can use the finally block which always executes whether the exception occurs or not.
  • Else: Instead of using the finally block, you can also use the else block right after a try-and-except block. It will help you to make sure that no exception occurs in the program, as it will only run when there is no exception.
  • Raise: One more exception handling is done by using the raise keyword, you can use it without using try and except block and just raise an exception that would most probably pop up.
Tip: It is important to use except block when you are using a try block. Many except blocks can be used with one try block

Understanding Exceptions

Exceptions in Python

Exception is like a situation that halts the normal flow of the program and stops the program in between without any reason. Exceptions are not related to the syntax error in the program but a run time issue. It will help the program to run smoothly and improve the robustness of the program. In Python, an exception is like a capsule that encapsulates the error events related to the program's abnormal behavior. When the Python compiler encounters a situation that cannot be handled on its own, it raises the exception by signaling the developer to resolve it.

Exploring Different Types of Exceptions

As we know there are two types of exceptions in Python, each has its use case and can be used by the developer in certain situations. These are:

  • Built-in Exception: A built-in exception is a type that is already defined in Python. These exceptions normally encounter errors by many of you, so Python developed the module based on it, which is helpful and time-saving.
  • User-defined exception Sometimes a situation occurs where you cannot handle it by the available built-in exceptions, therefore Python allows you to make the custom exception to handle this type of problem and the programmer has to define the exception on its own with coding.

Examples of Common built-in Exceptions

Python has a vast range of built-in exceptions. Each exception has been used for specific error occurrences. Each has its use case. So, let's explore each one of them:

1: Value Error

This exception occurs when the function gets an argument with the correct datatype, but the value of that datatype is invalid.

#here we pass the string to int datatype that is an invalid value 
number = int("string") 


2: Type Error

This exception occurs when the operation is performed on an incorrect type.

#here we perform an addition operation on a string with an int datatype that is inappropriate
number = 7 + "7" 


3: Assert Error

This exception occurs when the assert expression fails. Its main purpose is to debug and check expressions.

#here assertion error occurs because the expression fails 
assert 5!=5


4: Module Error

This exception occurs when you are trying to import the module, but Python cannot locate the module.

#here import cannot locate the specified module 
import module_Name 


5: Index Error

This exception occurs when you try to access the number from the list that is not added or out of range.

#here num_add variable tries to access the number at index 6 which is out of range 
number_list = [1,2,3,4,5] 
num_add = number_list[6] 


6: ZeroDivision Error

This exception normally occurs when you try to divide a number with the second operand as zero.

#here num variable stores the result by dividing the 10 by 0 
num  = 10/0


7: Name Error

This exception occurs when you try to use a variable that is not defined locally and globally in the program

#here when the variable is undefined, and you are trying to use it 
num = 10 
num2 = num/num3 


8: Syntax Error

This exception occurs when the incorrect syntax is not detected by the parse or interpreter before the code compilation.

#here syntax is incorrect 
num  10; 
num2 50; 
result 10 + 50


9: FileNotFound Error

This exception occurs when you try to open the file but it fails because the compiler cannot find the specific file in your program folder. This exception is the subclass of the OSError exception.

#Try to manipulate the file that is not available and cannot be found at the provided path 
def read_content_from_file(file_path):
    with open(file_path, 'r') as file:
        content =  file.readlines()
file_path = "file.txt"


10: Indentation Error

This exception usually occurs when you use incorrect indentation.

#IndentationError: incorrect indent/space is used at the return line 
def add(): 
    num1 = 7 
    num2 = 25 
    result = num1 + num2 
        return result
cal = add()
print("Sum of two numbers", cal)


Note: All exception types are objects because they are inherited from the exception base class.
FAQs Q: Can I create my exception?
A: Yes, you can define your custom-built exception class by inheriting it from the Exception base class.
Q: Is error or exception handling different?
A: Yes, there are many types of error that you can catch before compiling the code but sometimes the error occurs where only exception handling is required.
Q: Is it possible to execute the code regardless of checking error occurrence?
A: Yes, by using the finally block with the try and catch block you can execute the code that is written in the finally block because the finally block will execute whether the exception occurs or not.

Wrapping Up

In conclusion, we discussed the need for exception handling in the software development process before the program is released in the market or available for the user. As you know, exception handling is a powerful concept of programming language. It helps you as well as prepares you beforehand for future errors. Many built-in exceptions provided by Python cover most of your errors during the program development but you can also use the custom-based exception if you encounter a situation where no built-in exception is helpful, this problem is also resolved by the Python programming language. Now, I hope you will easily handle the exception in your code. Thank you for reading the guide. Happy Coding!


If you read this far, tweet to the author to show them you care. Tweet a Thanks

More Posts

Python Try Except Blocks

Abdul Daim - Mar 4

Opening & Reading Files Handling in Python

Abdul Daim - Apr 12

Python Finally Block

Abdul Daim - Mar 7

Checked exception is invalid for this method

prince yadav - Nov 26, 2023

Setting up Virtual Environment in Python

Tejas Vaij - Apr 20