Exception Treatment does not work when dividing by zero

Asked

Viewed 203 times

0

I need to read a set of values and report the division between them, regardless of whether they are positive or negative. The problem says that if there is a division by zero a message should be displayed saying "impossible division".

I decided to ask this question using the command try/except, since it is the only alternative that would not return an error message with a split by zero, but even using this command is being returned an error message and does not display the message the question asks.

N = int(input())

for i in range(0, N):
    try:
       X, Y = input().split(" ")

       X = float(X)
       Y = float(Y)
    except ZeroDivisionError:
       print('divisao impossivel')
    else:
       divisao = X / Y

       print(divisao)

1 answer

0


The division should be within the attempt, after the attempt is over and has already dealt with the possible mistake that has no way to happen, there is no point in making the division because there the error will not be dealt with. It would be something like that:

N = int(input())
for i in range(0, N):
    try:
       X, Y = input().split(" ")
       X = float(X)
       Y = float(Y)
       divisao = X / Y
       print(divisao)
    except ZeroDivisionError:
       print('divisao impossivel')

But that’s not right.

There are other errors that have not been dealt with, and it is complicated to deal with without the exception.

And I think an error that is easily detected should do so instead of letting the exception burst. So contrary to what is written in the question capture the exception is not the only alternative to solve this.

And if you make a mistake I imagine you shouldn’t go into counting items like you’re doing.

It’s not a mistake, but Python’s people picked up this sad way of getting the data in a row only that encourages typing wrong things. I would change that, but it may be that exercise asks like this, which is a way of teaching to do confusing things, I would rethink something that goes down this path as being a good reference.

Then it would almost be this;

n = int(input())
i = 0
while i < n:
    try:
        x, y = input().split(" ")
        x = float(x)
        y = float(y)
        if y != 0:
           print(x / y)
           i += 1
        else:
            print('divisao impossivel')
    except ValueError:
       print('formato digitado errado')

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Actually it can still give error when you type the n, make the treatment of this case.

  • Could you explain to me why this way of reading the data in a single line is not appropriate? My first programming language is Python.

  • Because it is very easy to type wrong, one has to know that one has to put a space.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.