Exception handling · Tratamento de exceções
| English | Português |
|---|---|
| exception/ekˈsepʃn/ | exceção |
| exception handling/ekˈsepʃn ˈhændlɪŋ/ | tratamento de exceções |
| raise/reɪz/ | elevam |
The check that cannot be written
- A program opens a file. Before opening it, you could check that the file exists, that it is readable, that the disk is present. Suppose every check passes.
- Between the last check and the open, a user pulls out the USB stick. The file existed when you asked and does not exist when you open it, and no amount of checking in advance could have closed that gap.
- Some errors are simply not preventable, because the world changes between the test and the action. What a program can do is respond to them when they happen.
- This lesson is the exception 异常, the TRY structure that handles one, and where in a program an exception should be caught.
A verificação que não pode ser escrita
- Um programa abre um arquivo. Antes de abri-lo, você poderia verificar se o arquivo existe, se é legível, se o disco está presente. Suponha que todas as verificações passem.
- Entre a última verificação e a abertura, o usuário retira o pendrive. O arquivo existia quando você perguntou e não existe quando você abre, e nenhuma quantidade de verificação antecipada poderia fechar essa lacuna.
- Alguns erros simplesmente não são preveníveis, porque o mundo muda entre o teste e a ação. O que um programa pode fazer é responder a eles quando ocorrem.
- Esta lição trata da exception 异常 (exceção), a estrutura TRY que a lida, e onde em um programa uma exceção deve ser capturada.
What an exception is and why handle it
- An exception is an error that occurs during execution: division by zero, a file not found, invalid input, a network that has gone away.
- Exception handling 异常处理 lets the program detect the error and respond in a controlled way, instead of crashing and losing the user's work.
- Real programs face errors that cannot be prevented in advance, as the hook shows. And without exceptions, every single operation would need its own
IFcheck around it, burying the actual algorithm in error tests. - The third benefit is the one the exam most often asks for: it separates the normal flow from the error handling, so the main path reads cleanly.
O que é uma exceção e porquê tratá-la
- Uma exceção é um erro que ocorre durante a execução: divisão por zero, arquivo não encontrado, entrada inválida, uma rede que desapareceu.
- Exception handling 异常处理 (tratamento de exceções) permite que o programa detecte o erro e responda de forma controlada, em vez de travar e perder o trabalho do usuário.
- Programas reais enfrentam erros que cannot be prevented in advance (não podem ser prevenidos antecipadamente), como o gancho mostra. E sem exceções, cada operação individual precisaria de sua própria
IFcheck (verificação) ao redor, enterrando o algoritmo real em testes de erro. - O terceiro benefício é aquele que o exame pede mais frequentemente: ele separates (separa) o fluxo normal do tratamento de erros, para que o caminho principal leia limpo.
An exception is: · Uma exceção é:
Exceptions are run-time problems (divide by zero, file not found) that handling lets you respond to gracefully. · Exceções são problemas de tempo de execução (divisão por zero, arquivo não encontrado) que o tratamento permite responder com elegância.
Why use exception handling rather than checking for every error in advance? Select all · todos that apply. · Por que usar tratamento de exceções em vez de verificar cada erro adiante? Selecione todos os que se aplicam.
The benefits are correctness and clarity. Speed is not one of them; handling adds a little overhead, which is worth paying. · Os benefícios são correção e clareza. Velocidade não é um deles; o tratamento adiciona uma pequena sobrecarga, que vale a pena pagar.
The TRY structure
- The TRY block holds the code that might fail. If it runs without error, the EXCEPT blocks are skipped entirely.
- If an exception occurs, execution jumps immediately to the first matching EXCEPT block. The rest of the TRY block does not run.
- A FINALLY block runs whether or not an exception happened, which makes it the right place for cleanup such as closing a file.
One path when all is well, another when it is not, and one that always runs
A estrutura TRY
TRY
OPENFILE "data.txt" FOR READ
READFILE "data.txt", line
CLOSEFILE "data.txt"
EXCEPT FileNotFound
OUTPUT "Sorry, the file does not exist."
EXCEPT ReadError
OUTPUT "Sorry, there was an error reading the file."
FINALLY
OUTPUT "Finished attempting to read."
ENDTRY
- O bloco TRY contém o código que pode falhar. Se rodar sem erro, os blocos EXCEPT são ignorados completamente.
- Se uma exceção ocorrer, a execução pula imediatamente para o primeiro bloco EXCEPT correspondente. O resto do bloco TRY não roda.
- Um bloco FINALLY roda seja ou não uma exceção tenha acontecido, o que o torna o lugar certo para limpeza, como fechar um arquivo.

Um caminho quando tudo está bem, outro quando não está, e um que sempre roda
How exception handling flows · Como o tratamento de exceções flui
Step through what happens when code fails. The exception jumps out of the normal flow to a handler, FINALLY cleans up either way, and the program carries on instead of crashing. · Passe passo a passo sobre o que acontece quando o código falha. A exceção salta fora do fluxo normal para um manipulador, FINALLY limpa de qualquer forma, e o programa continua em vez de travar.
Match each exception-handling keyword to its job. · Combine cada palavra-chave de tratamento de exceções com sua função.
TRY guards the risky code, EXCEPT catches, FINALLY cleans up either way, RAISE throws an error to be caught. · TENTAR protege o código arriscado, EXCEÇÃO captura, FINALLY limpa de qualquer forma, LANÇAR lança um erro para ser capturado.
A FINALLY block: · Um bloco FINALLY:
FINALLY always runs, making it ideal for cleanup such as closing files. · FINALLY sempre executa, tornando-o ideal para limpeza como fechar arquivos.
The block that runs whether or not an exception occurred, making it right for closing files, is ____. · O bloco que executa independentemente de uma exceção ter ocorrido, sendo perfeito para fechar arquivos, é ____.
Cleanup must happen on both paths. Putting CLOSEFILE only in the TRY block means it is skipped exactly when an error left the file open. · A limpeza deve acontecer nos dois caminhos. Colocar FECHARARQUIVO apenas no bloco TENTAR significa que ele é pulado exatamente quando um erro deixou o arquivo aberto.
Worked example: trace the flow
- In the code above, the file does not exist. State exactly what is output and what is skipped.
OPENFILEraises FileNotFound, so execution leaves the TRY block immediately: theREADFILEandCLOSEFILElines never run.- The
FileNotFoundEXCEPT block runs, outputting "Sorry, the file does not exist." TheReadErrorblock does not run, because only the first matching handler is used. - The FINALLY block runs, outputting "Finished attempting to read."
- The mark most often lost is noticing that the rest of the TRY block is abandoned.
Exemplo resolvido: traçar o fluxo
- No código acima, o arquivo não existe. Declare exatamente o que é output (impresso) e o que é skipped (omitido).
OPENFILEraises FileNotFound, então execution leaves the TRY block immediately: as linhasREADFILEeCLOSEFILEnunca rodam.- O bloco EXCEPT
FileNotFoundroda, outputting "Sorry, the file does not exist." O blocoReadErrornão roda, porque apenas o primeiro handler correspondente é usado. - O bloco FINALLY roda, outputting "Finished attempting to read."
- A marca mais perdida é notar que o resto do bloco TRY é abandonado.
The file in the TRY block does not exist. Put what happens in order. · O arquivo no bloco TENTAR não existe. Coloque o que acontece em ordem.
Only the first matching handler runs, and FINALLY runs either way. The skipped remainder of the TRY block is the mark most often missed. · Apenas o primeiro manipulador correspondente executa, e FINALLY executa de qualquer forma. O restante pulado do bloco TENTAR é a marca mais frequentemente perdida.
Raising an exception
- A subroutine that detects a problem it cannot sensibly deal with can raise 抛出 an exception, passing responsibility to whoever called it:
- This is the right design when the subroutine knows something is wrong but not what should be done about it. A division routine knows the divisor is zero; only the caller knows whether to ask the user again, use a default, or abandon the calculation.
Levantando uma exceção
- Uma subrotina que detecta um problema que não pode lidar sensivelmente pode raise 抛出 (levantar) uma exceção, passando responsabilidade para quem a chamou:
IF b = 0 THEN RAISE DivideByZero
- Este é o design certo quando a subrotina sabe que algo está errado, mas não o que deve ser feito sobre isso. Uma rotina de divisão sabe que o divisor é zero; apenas o caller (chamador) sabe se deve pedir ao usuário novamente, usar um padrão, ou abandonar o cálculo.
A subroutine uses RAISE to: · Uma subrotina usa LANÇAR para:
RAISE throws an exception up to the caller, which can catch it with EXCEPT. · LANÇAR levanta uma exceção para o chamador, que pode capturá-la com EXCEÇÃO.
Why would a division subroutine RAISE an exception instead of handling a zero divisor itself? · Por que uma subrotina de divisão LANÇARIA uma exceção em vez de lidar com o divisor zero ela mesma?
Ask the user again, use a default, or abandon the calculation: only the calling code has the context to choose. · Pedir ao usuário novamente, usar um padrão, ou abandonar o cálculo: apenas o código que chama tem o contexto para escolher.
Where to handle it
- Handle an exception close to where it occurs when the response is simple and local: print a message, use a default, ask the user to try again.
- Handle it higher up when the decision belongs to a larger part of the program: whether to abandon a whole transaction, roll back a change, or tell the user the operation failed.
- The rule of thumb: catch it at the level that has enough information to decide what to do, not at the level that first notices.
Onde lidá-la
- Lide com uma exceção close to where it occurs (perto de onde ocorre) quando a resposta é simples e local: imprima uma mensagem, use um padrão, peça ao usuário para tentar novamente.
- Lide com ela higher up (mais acima) quando a decisão pertence a uma parte maior do programa: se deve abandonar uma transação inteira, desfazer uma mudança, ou informar ao usuário que a operação falhou.
- A regra prática: capture-a no nível que tem informação suficiente para decidir o que do, não no nível que primeiramente percebe.
Worked example: what not to do
- A student writes
EXCEPT: (do nothing)around a whole program so it never crashes. Explain why this is poor practice. - The exception is swallowed: the program continues as though nothing went wrong, so it carries on with missing or invalid data and produces wrong results instead of an obvious failure.
- A silent failure is harder to diagnose than a crash, because there is no message and no indication of where it happened.
- Catching every exception in one place also means the specific error type is lost, so no sensible response can be chosen. A handler should catch a specific exception and actually respond to it.
Exemplo resolvido: o que não fazer
- Um aluno escreve
EXCEPT: (do nothing)ao redor de um programa inteiro para que nunca trave. Explique por que isso é má prática. - A exceção é swallowed (engolida): o programa continua como se nada tivesse dado errado, então continua com dados faltantes ou inválidos e produz resultados errados em vez de uma falha óbvia.
- Uma falha silenciosa é harder to diagnose (mais difícil de diagnosticar) do que um crash, porque não há mensagem e nenhuma indicação de onde aconteceu.
- Capturar todas as exceções em um único lugar também significa que o tipo específico de erro é perdido, então nenhuma resposta sensata pode ser escolhida. Um manipulador deve capturar uma exceção específica e realmente responder a ela.
Silently "swallowing" an exception (catching it but doing nothing) hides real errors and makes debugging hard — you should handle it or at least log it. · Silenciosamente "engolir" uma exceção (capturá-la mas não fazer nada) esconde erros reais e dificulta a depuração — você deve tratá-la ou pelo menos registrá-la.
An empty handler hides the very problems you need to find; always respond or record the error. · Um manipulador vazio esconde os próprios problemas que você precisa encontrar; sempre responda ou registre o erro.
Marks that slip away
- When an exception occurs, the rest of the TRY block is skipped. Say so when tracing.
- Only the first matching EXCEPT runs, not all of them.
- FINALLY always runs, error or no error, which is what makes it right for closing files.
- Do not catch an exception and do nothing. A swallowed error is worse than a crash, because the program continues with bad data.
Marcas que escapam
- Quando uma exceção ocorre, o resto do bloco TRY é pulado. Mencionar isso ao rastrear.
- Apenas o primeiro EXCEPT correspondente executa, não todos eles.
- FINALLY sempre executa, com ou sem erro, o que o torna adequado para fechar arquivos.
- Não capture uma exceção e não faça nada. Um erro engolido é pior que uma falha, porque o programa continua com dados incorretos.
You've got it
- an exception is a run-time error; handling it lets a program respond instead of crashing, covers errors that cannot be prevented in advance, and separates normal code from error handling
- TRY holds the risky code; on an error the rest of it is skipped and the first matching EXCEPT runs; FINALLY runs either way, so cleanup belongs there
- a subroutine that cannot decide the response should RAISE the exception for its caller
- handle it close by for a simple local response, higher up when the decision needs a wider view; never catch it and do nothing
Entendeu?
- uma exceção é um erro de tempo de execução; manipulá-la permite que um programa responda em vez de falhar, cobre erros que não podem ser prevenidos antecipadamente e separa o código normal do tratamento de erros
- TRY contém o código arriscado; em caso de erro, o resto é pulado e o primeiro EXCEPT correspondente executa; FINALLY executa de qualquer forma, então a limpeza pertence lá
- uma subrotina que não consegue decidir a resposta deve RAISE (lançar) a exceção para seu chamador
- manipule-a perto para uma resposta local simples, mais acima quando a decisão precisar de uma visão mais ampla; nunca a capture e não faça nada