Exception Handling in Python
An exception is an occurrence that takes place while a program is running and prevents the instructions from proceeding normally. Writing robust and error-free code requires understanding typical exceptions and knowing how to manage them.
To make sure that the program functions properly and according to plan, understanding how to handle exceptions is crucial. A good and effective coding process depends on knowing how to debug and fix exceptions. In this blog, you will get a comprehensive guide on exception handling in Python through examples.
How Do Exceptions Occur in Python?
Python exceptions occur while executing a code. A variety of factors, including syntax problems, wrong variable names, and type issues, might contribute to these errors. If an exception is found, the execution is interrupted and the interpreter searches for a code that can handle the exception.
Exceptions are represented in Python by classes, and each sort of exception has its own class. A ‘try…except’ block is used for exception handling, allowing the programmer to capture and deal with certain exceptions that may arise during program execution.
Different Types of Exceptions in Python
There are several different types of exceptions that can arise during an execution of a program. Here are some of the most commonly arising exceptions-
1. Syntax Error
This exception arises when the interpreter runs upon a syntax problem in the code, such as a misspelled word, a missing colon, or an unclosed pair of parentheses.
2. Type Error
When an operation or function is carried out on an object of the incorrect type, such as by adding a string to an integer, this error is triggered.
3. Name Error
When a variable or function is used before it has been defined, an exception is shown. You will see a NameError, for instance, if you attempt to print a variable that hasn’t been given a value.
4. Index Error
When an index for a list, tuple, or other sequence type is outside its acceptable range, this exception is returned. For instance, you will see an IndexError, if you attempt to access the ninth entry of a list that contains only four items.
5. Key Error
This exception is shown when a key cannot be located in a dictionary.
6. Value Error
When a method or action is applied to an object with an improper value, this exception is triggered. For instance, if you attempt to use the int() function to convert a string that cannot be converted to an integer, a ValueError will be returned.
7. Attribute Error
Accessing a method or property that doesn’t exist on an object will result in this exception.
8. ZeroDivisionError
This exception is shown when a number is divided by 0. For instance, if you attempt to divide 3 by 0.
To learn more about the different types of exceptions in Python and how to counter them, try a Python programming course which will help you get an in-depth understanding of the concept.
How to Handle Exceptions in Python?
Exception handling in Python uses the mechanisms mentioned below-
1. Try
The ‘try’ block is used in Python to contain code that may throw an exception. Let’s see an example,
try:
print(x)
except NameError:
print("You have not defined Variable x")
except:
print("Something in your code is wrong")
2. Except
We use the ‘except’ keyword instead of ‘catch’ in Python, to catch and handle exceptions. The exceptions raised in the try block are handled by the except block. Let’s see an example,
try:
result = 10/0
except ZeroDivisionError:
print("Cannot divide by zero")
3. Finally
The ‘finally’ block in Python is used to describe code that should be executed regardless of whether or not an exception is triggered. Let’s see an example,
try:
f = open("samplefile.txt")
try:
f.write("Lorem Ipsum")
except:
print("Something went wrong while writing on the file")
finally:
f.close()
except:
print("We can not open your file")
You can also read about Python data types, to understand better how to better handle exceptions in Python.
Exception Handling in Python With Example
Here are two different examples of exceptions and how to handle them in Python:
Example 1 – Handling Type Error
In this example, the TypeError exception that can pop up when attempting to execute an operation on incompatible data types is handled using a ‘try…except’ block.
try:
name = input("Enter name: ")
age = int(input("Enter age: "))
message = "Hello, " + name + ". You are " + age + " years old."
print(message)
except TypeError:
print("Error: incompatible data types")
We attempt to concatenate a string and an integer in this piece of code. Due to the fact that we cannot concatenate a string and an integer, this would result in a ‘TypeError’ error. We apply a ‘try…except’ block to handle this exception, which captures the ‘TypeError’ exception and outputs a unique error message to the console.
Example 2 – Handling ZeroDivisionError
In this example, we demonstrate how to handle the ‘ZeroDivisionError’ exception that could occur when attempting to divide a number by zero using a ‘try…except’ block.
try:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
result = num1 / num2
print("Result = ", result)
except ZeroDivisionError:
print("Error: division by zero")
except ValueError:
print("Error: invalid input")
except Exception as e:
print("An error occurred:", e)
finally:
print("This block always executes")
Advantages of Exception Handling in Python
Exception handling allows developers to handle problems in a controlled and reliable manner, improving program stability. Besides this, there are several advantages of exception handling in Python. Some of them include:
1. Cleaner Code
Using ‘try…except’ blocks to handle exceptions can improve the readability of your code by making it clear which parts of your code are in control of error handling. This can help other developers understand and work with your code more easily.
2. Easy Debugging
When an exception occurs, python provides a complete trail that shows exactly where the error occurred, which makes it a lot easier to debug your code.
3. Better Error Handling
Exception handling allows you to recover from problems and continue running your program instead of having it crash or terminate abruptly. This can improve the user experience by minimizing disruption while yet allowing the program to function.
4. Better Code Reliability
Exception handling improves the reliability of your code by preventing unexpected failures from causing your program to crash. You can write more resilient and less likely-to-fail code by predicting and handling potential exceptions.
Conclusion
Exception handling in Python assists developers in writing robust and dependable code. The built-in exception-handling functionality of Python enables programmers to catch and manage a variety of problems, including custom exceptions. It provides a framework for dealing with faults and unforeseen conditions that may arise during program execution.