What is the function of "Try" and "except"

Asked

Viewed 21,590 times

10

Could someone answer me what the parameter means try: and the except?

I need to do a show and I have a question about this.

  • Know the concept of exception?

  • https://answall.com/q/314111/101 and https://answall.com/questions/tagged/exce%C3%A7%C3%a3o? Sort=votes&pageSize=50

2 answers

16


The try/except is used for handling exceptions.

Exception is when a thing does not occur as planned. It can be said that the programs have a normal flow, and an exceptional flow which are the exceptions.

The syntax is

try:
    código a tentar
except AlgumaExcecao:
    código a executar no caso da exceção
else:
    código a executar caso não ocorra exceção em try
finally:
    código que é executado sempre, independente de haver uma exceção em andamento ou não

Python functions already automatically raise exceptions when something happens, for example if you try to open a file and it doesn’t exist:

try:
    f = open('arquivo')
except OSError:
    print('Nao deu pra abrir o arquivo')
else:
    print('Arquivo aberto!')

You can even raise exceptions in your code, to notify the user of its functions of some exceptional behavior

class DeuProblema(Exception): pass

def faz_alguma_coisa():
    ...
    if ...:
        raise DeuProblema()
    ...

Hence who is using:

try:
    faz_alguma_coisa()
except DeuProblema:
    tenta_outra_coisa()

Another very common use is to make sure that a certain code will run:

d = abre_banco_de_dados() # precisa ser fechado
try:
    ...
finally:
    d.close() # garante que o banco será fechado mesmo em caso de erro

Finally, an important tip. Do not use except pure in this way:

try:
    ...
except:  # pega qualquer exceção (EVITE!)
    ...

This kind of construction hides any and all mistakes making it very difficult to develop the program, because the errors will be silenced. Also you can catch exceptions that you don’t want to capture as for example KeyboardInterrupt or MemoryError. Instead always pass the exception you want to take, or use Exception to catch most of the exceptions.

try:
    ...
except ValueError:  # pega somente ValueError
    ...
except Exception:  # não pega MemoryError, SystemExit, KeyboardInterrupt
    log.exception()
    raise # sempre suba novamente a exceção não tratada, 
          # para que seja visível

4

The idea of Try except is to test critical points of code, i.e., places where there is great possibility of errors.

They are widely used in reading files or user input data. For example, you want the user to type an integer to perform a mathematical operation, if it type a string, the operation will not work.

def div(a,b):
    try:
        x = a/b
        return x
    except:
        return "Nao foi possivel realizar a operacao"

When calling the function this way, the return will be an integer value (in this case, 4)

div(20,5)

When to call for

div('a','b')

The return will be the message It was not possible to perform the operation

Browser other questions tagged

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