Solution using the Try Except Method

In this example, you can see two cases of the Python Try-Except method. One which leads to an exception and another which will run without any exception. In the code, you can see how we are handling the error. (Here we are aware of the error we are going to encounter).

Example 1:

In the code, you can see how we are handling the error, Here we are aware of the error we are going to encounter.

Python3




def divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        result = 0
    return result
  
print(divide(3, 0))
print(divide(4, 2))


Output:

0
2.0

Example 2:

In this example, let’s assume we are unaware of the error we are going to encounter. Here we can see that the specified error is not given. This might not be a good practice, because it becomes hard to trace the exact issue in the code. 

Python3




def divide(a, b):
    try:
        result = a / b
    except:
        result = 0
    return result
  
print(divide(3, 0))
print(divide(4, 2))


Output:

0
2.0

How to Ignore an Exception and Proceed in Python

There are a lot of times when in order to prototype fast, we need to ignore a few exceptions to get to the final result and then fix them later. In this article, we will see how we can ignore an exception in Python and proceed. 

Similar Reads

Demonstrate Exception in Python

Before seeing the method to solve it, let’s write a program to raise an error....

Solution using the Try Except Method

...

Solution Using Suppress Function

In this example, you can see two cases of the Python Try-Except method. One which leads to an exception and another which will run without any exception. In the code, you can see how we are handling the error. (Here we are aware of the error we are going to encounter)....