Jump to content

Try/exception


jonhhy

Recommended Posts

Bom dia Comunidade Portugal-a-Programar,


é possível colocar as exception's dentro dos if's de modo a executar somente uma exception?
Pois neste trecho de código:

def readIntandFloat():
  try:
    i = int(input('Tell me a int: '))
  except(ValueError, TypeError):
    print("\033[0;30;41mError: The data type that you enter did not numeric as expected for this purpose.")
    return readIntandFloat()
  # finally:
  #   print('')
  try:
    f = float(input('Tell me a number: '))
  except(ValueError, TypeError):
    print("\033[0;30;43mError: The data type that you enter did not numeric as expected for this purpose.")
    readFloat('Tell me a number2: ') 
  except(KeyboardInterrupt):
    print('\033[0;30;44mError: Not inform more data')
    readFloat('Tell me a number2: ') # return
  else:
    print(f'The int number is {i} and \t The float number is {f}')
  finally:
     print('Felizes e contentes')

que usa esta função:

 

def readFloat(msg):
  try:
    inp = float(input(msg))
  except KeyboardInterrupt: # para funcionar tinha no meio de dois input's como acontece no exemplo acima!
    print("\033[0;30;42mUser didn't inform the data")
    readFloat('Error: Digit a new number: ')
  except(ValueError, TypeError):
    print("\033[0;30;47mThe data type that you enter did not numeric as expected for this purpose")
    readFloat('Error: Digit a number again: ')
  except  Exception as general:
    print(f'The problem was {general.__class__}')
  else:
    print(f'The number is {inp}')
Tell me a int: 6
Tell me a number: 
Error: The data type that you enter did not numeric as expected for this purpose.
Tell me a number2: t
The data type that you enter did not numeric as expected for this purpose
Error: Digit a number again:  
The data type that you enter did not numeric as expected for this purpose
User didn't inform the data
Error: Digit a new number: 9
The number is 9.0
Felizes e contentes
Error: Digit a number again
Error: Digit a number again: 
Error: Digit a new number: 

O programa ao entrar nesta função, sempre que tento parar a execução do trabalho, ele abre 2 abas de input!

.. e preenchendo uma delas  acontece isto

User didn't inform the data
Error: Digit a number again: 9
The number is 9.0
Felizes e contentes
Error: Digit a new number: 

A pergunta acima na minha óptica pode resolver a questão, mas gostava de muito a vossa opinião.

 

cumprimentos

Edited by jonhhy
Link to comment
Share on other sites

Podes explicar qual é o objetivo desse código? Qual é o fluxo de funcionamento esperado a fim de alcançar esse objetivo? Deverá haver alguma forma mais elegante de alcançar o que desejas.

Mais, não entendi exactamente o que queres dizer com "excepção dentro do if". Se for isto...

try:
  foo1()
  if bar():
    except Exception as ex:   # Excepção dentro de um if
      print("pois")
  else:
    foo2()
finally:
  print("fim")

... então não, não é possível. O try, os respectivos exceptfinally opcional devem estar todos ao mesmo nível de indentação.

Cumprimentos.

Knowledge is free!

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.