except | What is Wrong With Using a Bare ‘except’?

In this tutorial, we will learn What is wrong with using a bare ‘except’ as bare except catches all the exceptions that would occur and it could catch the exception which you might not have expected
which makes it much more complex and hard to debug the code if an exception had occurred.

except

It is recommended that we must use the specific excepts so that w could find out where exactly the exception has occurred and we could find out during debugging the code directly instead of going through all the code to find the problem.

 

Except

As it is the keyword used for catching exceptions in python where after the keyword we need to put the name of the exception that we care trying to catch as it helps in getting to during the debugging as we could easily find where exactly the error has occurred to generally we take the path which makes our path easier further.

However, in the case of bare except it will keep on catching the exception whenever it is occurring irrespectively of why is it occurring means we could not find the cause if we use bare except as in every case the output will be the same so it is generally said to be the wrong way of using except.

To look at how we need to use except in python so that it would be easier to debug as it will be identified easily, more over to learn more and experience an example look at the example code given below.

try:
    x = int(input(" Enter a number: "))
    y = 10 / x
except:
    print(" Something went wrong")

Here it will give an exception but the reason would not be known as it will simply catch all the exceptions. But if we want it could catch only specific exceptions and put the output according to that then we need to follow another way for which the example code is given below.

try: 
    x = int(input(" Enter a number: "))
    y = 10 / x
except ValueError:
    print(" Invalid input. Please enter an integer.")
except ZeroDivisionError:
    print(" Cannot divide by zero.")
else:
    print(f" 10 divided by {x} is {y}.")

 

 

To learn more about what makes it much more complex and hard to debug the code if an exception had occurred visit: bare except in python with its drawbacks.

To learn more about different other solutions to the problems faced in python visit: Python Tutorials And Problems.

And to learn more about different other programming language solutions and the tutorial to the concepts visit: beta python programming languages Solutions.

Leave a Comment

%d bloggers like this: