In the previous tutorial, we learn about List comprehensions and generators in Python (With Examples). So, now we are going to discuss Exception handling in python.
Exception handling is a critical programming aspect that allows developers to handle unforeseen errors and exceptions during program execution. In Python, exception handling is done using the try/except statement.
Python try…except Block:
The try/except statement allows developers to define a block of code that may raise an exception.
try:
# code that may cause exception
except:
# code to run when exception occurs
If an exception is raised, the code within the try block is aborted, and the code within the except block is executed. The except block should contain code that can handle the specific exception that was raised.
Exception handling using (try…except):
Here is an example to briefly understand exception handling in python.
Code:
a = 10
b = 0
try:
result = a / b
except ZeroDivisionError:
print("Error: division by zero")
Output:
Error: division by zero
In this example, the code within the try block attempts to divide the variable a by the variable b. However, since b is zero, a ZeroDivisionError exception is raised. The except block contains code that prints an error message indicating that a division by zero has occurred.
Types of Exception Handling in Python (With Examples):
Now we are going to explain all the types of exception handling (try…except in python with examples.
Handling a ZeroDivisionError in Python:
In this example, we are going to discuss ZeroDivisionError in python in detail.
Code:
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Output:
Cannot divide by zero
In this code, we will divide 1 by 0, which is impossible. It raises a ZeroDivisionError.
We use a try-except block to catch this exception and print an error message instead of letting the error crash the program.
Handling a TypeError in Python:
In this example, we are going to discuss TypeError in python in detail.
Code:
try:
x = "hello" + 1
except TypeError:
print("Cannot concatenate a string and an integer")
Output:
Cannot concatenate a string and an integer
This code attempts to concatenate a string (“hello”) and an integer (1), which is not possible. So, it raises a TypeError.
We use a try-except block to catch this exception. So, we print an error message instead of letting the error crash the program.
Handling a ValueError in Python:
In this example, we are going to discuss ValueError in python in detail.
Code:
try:
x = int("hello")
except ValueError:
print("Cannot convert 'hello' to an integer")
Output:
Cannot convert 'hello' to an integer
This code attempts to convert the string “hello” to an integer using the int() function, which is impossible and raises a ValueError.
We use a try-except block to catch this exception and print an error message instead of letting the error crash the program.
Handling a NameError in Python:
Now In this example, we are going to discuss NameError in python in detail.
Code:
try:
print(y)
except NameError:
print("Variable 'y' is not defined")
Output:
Variable 'y' is not defined
This code attempts to print the value of a variable y, which has not been defined, and raises a NameError.
We use a try-except block to catch this exception and print an error message instead of letting the error crash the program.
Handling a generic Exception in Python:
In this code, we are going to discuss generic Exception in python in detail.
Code:
try:
x = 1 / 0
except Exception as e:
print("An error occurred:", e)
Output:
An error occurred: division by zero
This code attempts to divide 1 by 0, which is impossible, and raises a ZeroDivisionError.
Instead of specifying the specific exception to catch, we use the generic Exception class to detect any type of exception.
We also use the as a keyword to give the exception object a name (e) so we can print a more informative error message.
I hope this helps explain how exception handling works in Python using the try-except statement.
So, in the next tutorial, we are going to learn about Assertions and Defensive Programming in python. So, make sure to subscribe to us to learn python in an easy way.