O código a seguir é bastante autoexplicativo: basta copiar e colar tudo em um módulo e executá-lo , ele fornece alguns casos de uso e muitos comentários explicativos no texto. (Funciona, mas estou interessado em saber o que outras pessoas acham disso e em quaisquer sugestões que você queira fazer.)

Os fatos mais importantes a serem percebidos são:

  1. Quando você usa em erro goto Label1, o procedimento entra em um estado de “Estou tratando de um erro”, pois uma exceção foi levantada. Quando está neste estado, se outra instrução “On Error Goto” label2 for executada, ela NÃO irá para label2, mas gerará um erro que será passado para o código que chamou o procedimento.

  2. Você pode interromper um procedimento que está no estado “Estou tratando de um erro” limpando a exceção (definindo err como nada para que a propriedade err.number se torne 0) por usando

    Err.clear or On Error Goto -1 " Which I think is less clear! 

(NOTE que On Error Goto 0 é diferente do anterior)

Também é importante notar que Err.Clear o redefine para zero, mas na verdade é equivalente a:

On Error Goto -1 On Error Goto 0 

ou seja, Err.Clear remove um “On Error Goto” que está em vigor. Portanto, é melhor usar principalmente:

On Error Goto -1 

como usando Err.clear Você frequentemente precisa escrever

Err.Clear On Error Goto MyErrorHandlerLabel 

Eu uso as técnicas acima com vários rótulos para simular a funcionalidade às vezes útil que os blocos TRY CATCH do Visual basic fornecem, que eu acho que têm seu lugar na escrita código legível.

É certo que essa técnica cria algumas linhas de código a mais do que uma boa instrução VB try catch, mas não é muito confusa e muito fácil de entender r cabeça ao redor.

PS. Também pode ser de interesse o procedimento ManageErrSource que faz com que a propriedade Err.Source armazene o procedimento onde ocorreu o erro.

Option Compare Database Option Explicit Dim RememberErrNumber As Long Dim RememberErrDescription As String Dim RememberErrSource As String Dim RememberErrLine As Integer Private Sub RememberThenClearTheErrorObject() On Error Resume Next " For demo purposes Debug.Print "ERROR RAISED" Debug.Print Err.Number Debug.Print Err.Description Debug.Print Err.Source Debug.Print " " " This function has to be declared in the same scope as the variables it refers to RememberErrNumber = Err.Number RememberErrDescription = Err.Description RememberErrSource = Err.Source RememberErrLine = Erl() " Note that the next line will reset the error object to 0, the variables above are used to remember the values " so that the same error can be re-raised Err.Clear " Err.Clear is used to clear the raised exception and set the err object to nothing (ie err.number to 0) " If Err.Clear has not be used, then the next "On Error GoTo ALabel" that is used in this or the procedure that called it " will actually NOT pass execution to the ALabel: label BUT the error is paseed to the procedure that called this procedure. " Using Err.Clear (or "On Error GoTo -1 ") gets around this and facilitates the whole TRY CATCH block scenario I am using there. " For demo purposes Debug.Print "ERROR RAISED is now 0 " Debug.Print Err.Number Debug.Print Err.Description Debug.Print Err.Source Debug.Print " " " For demo purposes Debug.Print "REMEMBERED AS" Debug.Print RememberErrNumber Debug.Print RememberErrDescription Debug.Print RememberErrSource Debug.Print " " End Sub Private Sub ClearRememberedErrorObjectValues() " This function has to be declared in the same scope as the variables it refers to RememberErrNumber = 0 RememberErrDescription = "" RememberErrSource = "" RememberErrLine = 0 End Sub Sub ExampleOfTryCatchBlockInVBA() On Error GoTo HandleError " ----------------------------------------------------- " SubProcedure1 has the example of a multiple line TRY block with a block of code executed in the event of an error SubProcedure1 Exit Sub HandleError: Select Case Err.Number Case 0 " This shold never happen as this code is an error handler! " However if it does still allow the Err.raise to execute below. (In this case Err.raise will fail " and itself will raise an error "Invalid procedure call or argument" indicating that 0 cannot be used to raise and error! Case 111111 " You might want to do special error handling for some predicted error numbers " perhaps resulting in a exit sub with no error or " perhaps using the Err.raise below Case Else " Just the Err.raise below is used for all other errors End Select " " I include the procedure ManageErrSource as an exmple of how Err.Source can be used to maintain a call stack of procedure names " and store the name of the procedure that FIRST raised the error. " Err.Raise Err.Number _ , ManageErrSource("MyModuleName", Err.Source, Erl(), "tsub1_RaisesProcedureNotFoundError") _ , Err.Number & "-" & Err.Description " Note the next line never gets excuted, but I like to have resume in the code for when I am debugging. " (When a break is active, by moving the next executable line onto it, and using step over, it moves the exection point to the line that actually raised the error) Resume End Sub Sub SubProcedure1() " ----------------------------------------------------- " Example of a multiple line TRY block with a Case statement used to CATCH the error " " It is sometimes better to NOT use this technique but to put the code in it"s own procedure " (ie I refer to the code below that is surrounded by the tag #OWNSUB) . " However,sometimes using this technique makes code more readable or simpler! " Dim i As Integer " This line puts in place the defualt error handler found at the very foot of the procedure On Error GoTo HandleError " " Perhaps lots of statements and code here " " First an example with comments " ----------------------------------------------------- " TRY BLOCK START " This next line causes execution to "jump" to the "catch" block in the event an error is detected. On Error GoTo CatchBlock1_Start " #OWNSUB tsub_WillNotRaiseError_JustPrintsOk If vbYes = MsgBox("1. Do you want to raise an error in the try block? - (PRESS CTRL+BREAK now then choose YES, try no later.)", vbYesNo) Then i = 100 / 0 End If " " Perhaps lots of statements and code here " " #OWNSUB " TRY BLOCK END " ----------------------------------------------------- " ----------------------------------------------------- " CATCH BLOCK START CatchBlock1_Start: If Err.Number = 0 Then On Error GoTo HandleError " Re-instates the procedure"s generic error handler " This is also done later, but I think putting it here reduces the likelyhood of a coder accidentally removing it. Else " WARNING: BE VERY CAREFUL with any code that is written here as " the "On Error GoTo CatchBlock1_Start" is still in effect and therefore any errors that get raised could goto this label " and cause and infinite loop. " NOTE that a replacement "On Error Goto" cannot be executed until Err.clear is used, otherwise the "On Error Goto" " will itself raise and error. " THEREFORE KEEP THE CODE HERE VERY SIMPLE! " RememberThenClearTheErrorObject should be the only code executed and this called procedure must be tight! " This saves the details of the error in variables so that the "On Error GoTo HandleError" can be used " to determine how the next Err.Raise used below is handled (and also how any unexpected implicitly raised errors are handled) RememberThenClearTheErrorObject On Error GoTo HandleError "#THISLINE# If vbYes = MsgBox("2. Do you want to raise an error in the erro handler? - (PRESS CTRL+BREAK now then try both YES and NO )", vbYesNo) Then i = 100 / 0 End If Select Case RememberErrNumber Case 0: " No Error, do Nothing Case 2517 Debug.Print "The coder has decided to just give a Warning: Procedure not found " & Err.Number & " - " & Err.Description ClearRememberedErrorObjectValues " Not essential, but might save confusion if coding errors are made Case Else " An unexepected error or perhaps an (user) error that needs re-raising occurred and should to be re-raised " NOTE this is giving an example of what woudl happen if the CatchBlock1_ErrorElse is not used below If vbYes = MsgBox("3. Do you want to raise an error in the ELSE error handler? CatchBlock1_ErrorElse *HAS NOT* been used? - (PRESS CTRL+BREAK now then try both YES and NO )", vbYesNo) Then i = 100 / 0 End If On Error GoTo CatchBlock1_ErrorElse " SOME COMPLEX ERROR HANDLING CODE - typically error logging, email, text file, messages etc.. " Because the error objects values have been stored in variables, you can use " code here that might itself raise an error and CHANGE the values of the error object. " You might want to surround the code with the commented out CatchBlock1_ErrorElse lines " to ignore these errors and raise the remembered error. (or if calling a error handling module " just use on error resume next). " Without the CatchBlock1_ErrorElse lines any error raised in this "complex code" will be handled by the " active error handler which was set by the "On Error GoTo HandleError" tagged as "#THISLINE#" above. If vbYes = MsgBox("4. Do you want to raise an error in the ELSE error handler when CatchBlock1_ErrorElse HAS been used? - (PRESS CTRL+BREAK now then try both YES and NO )", vbYesNo) Then i = 100 / 0 End If CatchBlock1_ErrorElse: On Error GoTo HandleError " This line must be preceeded by an new "On error goto" for obvious reasons Err.Raise RememberErrNumber, RememberErrSource, RememberErrDescription End Select On Error GoTo HandleError End If " CATCH BLOCK END " ----------------------------------------------------- On Error GoTo HandleError " Unnecessary but used to delimt the catch block " " lots of code here perhaps " " ----------------------------------------------------- " Example 2 " " In this example goto statements are used instead of the IF statement used in example 1 " and no explanitory comments are given (so you can see how simple it can look) " " ----------------------------------------------------- " TRY BLOCK START On Error GoTo CatchBlock2_Start tsub_WillNotRaiseError_JustPrintsOk If vbYes = MsgBox("Do you want to raise an error? - (PRESS CTRL+BREAK now then choose YES)", vbYesNo) Then i = 100 / 0 End If " " Perhaps lots of statements and code here " " TRY BLOCK END " ----------------------------------------------------- GoTo CatchBlock2_End: CatchBlock2_Start: RememberThenClearTheErrorObject On Error GoTo HandleError Select Case RememberErrNumber Case 0: " No Error, do Nothing Case 2517 Debug.Print "The coder has decided to just give a Warning: Procedure not found " & Err.Number & " - " & Err.Description ClearRememberedErrorObjectValues " Not essential, but might save confusion if coding errors are made Case Else " An unexepected error or perhaps an (user) error that needs re-raising occurred and should to be re-raised " In this case the unexpecetd erro will be handled by teh code that called this procedure " This line must be preceeded by an new "On error goto" for obvious reasons Err.Raise RememberErrNumber, RememberErrSource, RememberErrDescription End Select On Error GoTo HandleError End If CatchBlock2_End: " CATCH BLOCK END " ----------------------------------------------------- On Error GoTo HandleError " Unnecessary but used to delimt the catch block " " Here you could add lots of lines of vba statements that use the generic error handling that is after the HandleError: label " " " " You could of course, alway add more TRY CATCH blocks like the above " " Exit Sub HandleError: Select Case Err.Number Case 0 " This shold never happen as this code isan error handler! " However if it does still allow the Err.raise to execute below. (In this case Err.raise will fail " and itself will raise an error "Invalid procedure call or argument" indicating that 0 cannot be used to raise and error! Case 111111 " You might watch to do special error handling for some predicted error numbers " perhaps exit sub " Perhaps using the Err.raise below End Select " ie Otherwise " " Note that I use the Err.Source to maintain a call stack of procedure names " Err.Raise Err.Number _ , ManageErrSource("MyModuleName", Err.Source, Erl(), "tsub1_RaisesProcedureNotFoundError") _ , Err.Number & "-" & Err.Description " Note the next line never gets excuted, but I like to have resume in the code for when I am debugging. " (By moving the next executable line onto it, and using step over, it moves the exection point to the line that actually raised the error) Resume End Sub Sub tsub_WillNotRaiseError_JustPrintsOk() Static i As Integer i = i + 1 Debug.Print "OK " & i End Sub Public Function ManageErrSource(MyClassName As String, ErrSource As String, ErrLine As Integer, ProcedureName As String) As String " This function would normally be in a global error handling module " On Error GoTo err_ManageErrSource Const cnstblnRecordCallStack As Boolean = True Select Case ErrSource Case Application.VBE.ActiveVBProject.Name " Err.Source is set to this value when a VB statement raises and error. eg In Access by defualt it is set to "Database" ManageErrSource = Application.VBE.ActiveVBProject.Name & " " & MyClassName & "." & ProcedureName & ":" & ErrLine Case "" " When writing code ouside of the error handling code, the coder can raise an error explicitly, often using a user error number. " ie by using err.raise MyUserErrorNumber, "", "My Error descirption". " The error raised by the coder will be handled by an error handler (typically at the foot of a procedure where it was raised), and " it is this handler that calls the ManageErrSource function changing the Err.Source from "" to a meaningful value. ManageErrSource = Application.VBE.ActiveVBProject.Name & " " & MyClassName & "." & ProcedureName & ":" & ErrLine Case Else " This code is executed when ManageErrSource has already been called. The Err.Source will already have been set to hold the " Details of where the error occurred. " This option can be used to show the call stack, ie the names of the procdures that resulted in the prcedure with the error being called. If cnstblnRecordCallStack Then If InStr(1, ErrSource, ";") = 0 Then ManageErrSource = ErrSource & ":: Called By: " End If ManageErrSource = ErrSource & ";" & ProcedureName & ":" & ErrLine Else ManageErrSource = ErrSource End If End Select Exit Function err_ManageErrSource: Err.Raise Err.Number, "MyModuleName.err_ManageErrSource", Err.Description Resume End Function 

Comentários

  • Apenas dois comentários: 1 Por que diabos você usaria isso? 2 On Error Goto -1
  • Try / catch também pode ser emulado envolvendo o código relevante com On Error Resume Next e On Error GoTo 0 e verificando o Err.Number. O texto acima é um tanto difícil de acompanhar, tem um pouco de uma spaghetti estrutura.
  • Obrigado Rory, eu ‘ eu mudei. Você o usaria ou pelo mesmo motivo que qualquer um usaria uma instrução TRY CATCH em VB ou SQL Server. ou seja, permite que você estruture seu código de maneira diferente. ou seja, você pode usar o mesmo manipulador de erros para muitas linhas de código sem ter que colocar as linhas em seus próprios procedimentos.
  • Loannis. sim, ‘ já fiz isso no passado, para linhas únicas de código que precisam de um manipulador de erros. Ou seja, uma linha de código tem um manipulador de erros. TRY CATCH permite que um bloco de código (com muitas linhas) seja embutido em um procedimento com seu próprio ‘ manipulador de erros. Eu uso muito TRY CATCH no SQL Server e, como ‘ também está disponível em VB, deve servir a algum propósito geralmente útil. É certo que esta versão é um pouco confusa.
  • @Loannis E se você quiser pular várias linhas ao receber um erro. Veja minha resposta para um exemplo simplificado. Claro, você também pode fazer isso com o tratamento de erros regular.

Resposta

O problema é que os erros de tempo de execução em VBA não são exceções , e o tratamento de erros em VBA tem muito pouco em comum com o tratamento de exceções.

RememberErrLine = Erl() 

O Erl função é um membro oculto do módulo VBA.Information por uma razão – retorna 0 a menos que o erro tenha ocorrido em uma linha numerada. E se você estiver usando números de linha em VBA, você mora em uma caverna há 25 anos e provavelmente está usando GoSub instruções em vez de escrever procedimentos. Números de linha são permitidos por motivos de compatibilidade legada / com versões anteriores , porque o código escrito nos anos 1980 exigia deles.

Gosto de como você mesmo disse:

" THEREFORE KEEP THE CODE HERE VERY SIMPLE! 

..mas por que isso não se aplica ao resto do código? Sem ofensa, mas esta é a lógica espaguete, escrita em procedimentos que violam clara e descaradamente os Princípio de responsabilidade única . Nenhum código compatível com SRP precisaria de dois desses blocos ” try-catch “.

Isso cheira a:

Case 0: " No Error, do Nothing 

Significa uma de duas coisas: ou você tem um código de tratamento de erros que é executado em contextos sem erros, ou você tem um código morto que deve ser excluído.

Isso cheira cheira mal :

GoTo CatchBlock2_End: CatchBlock2_Start: 

Em primeiro lugar, ac olon (:) que não especifica um rótulo de linha , é um separador de instruções .Acontece que uma nova linha também é um ” separador de instruções “, portanto, os dois pontos no final de GoTo CatchBlock2_End é totalmente inútil e confuso, especialmente dado o nível de indentação da instrução GoTo .

Falando em GoTo

Neil Stephenson acha que é fofo chamar seus rótulos de” dengo “

Não gosto de como preciso saltar entre os rótulos para seguir o código. IMO, ele é bagunçado e desnecessariamente complicado.


Tudo bem, sabichão . Então, como lidar de forma limpa com os erros no VBA?

1. Escreva um código limpo em primeiro lugar.

Siga as práticas recomendadas e escreva pequenos procedimentos que fazem uma coisa e fazem bem.

2. Escreva código orientado a objeto.

Abstração e encapsulamento são dois dos 4 pilares da OOP , e são totalmente compatíveis com VBA. Polimorfismo também é uma opção; apenas a herança adequada é descartada, mas isso não impede que se abstraiam conceitos em módulos de classe e instanciar objetos especializados.

O código de procedimento escrito em módulos padrão (.bas) deve ser um método público minúsculo (macro ” hooks “) que criam os objetos necessários para executar a funcionalidade.

Então, como isso se relaciona, mesmo remotamente, com o tratamento de erros adequado?

3. Aceite o tratamento de erros idiomáticos, não lute contra eles.

Dado o código que segue os pontos acima, não há razão para não implementar o tratamento de erros a maneira idiomática do VBA.

Public Sub DoSomething() On Error GoTo CleanFail "method body CleanExit: "cleanup code goes here. runs regardless of error state. Exit Sub CleanFail: "handle runtime error(s) here. "Raise Err.Number ""rethrow" / "bubble up" Resume CleanExit Resume "for debugging - break above and jump to the error-raising statement End Sub 

Este padrão é análogo a ” try-catch-finally ” da seguinte maneira:

  • O corpo é o ” try ” parte, que faz o que o nome do método diz e nada mais
  • CleanFail é o ” catch ” parte, que só é executada se um erro for gerado
  • CleanExit é a parte ” finalmente “, que é executada independentemente de haver ou não um erro foi gerado … a menos que você esteja relançando . Mas, se você precisar enviar um erro para o código de chamada lidar, você não deve ter muita limpeza c ode executar, e você deve ter uma razão muito, muito boa para fazê-lo.

Se sua sub-rotina de tratamento de erros pode gerar um erro, então você não está aderindo ao SRP. Por exemplo, gravar em um arquivo de log é uma preocupação própria, que deve ser abstraída em algum objeto Logger que vive para lidar com questões de registro e expõe métodos que tratam de seus próprios erros . O código da sub-rotina de tratamento de erros deve ser trivial.

Comentários

  • Obrigado @mat ‘ presunçoso por aceitar o tempo para adicionar comentários que realmente me ajudaram, eu ‘ estou pronto para críticas violentas, mas engraçadas. Eu ‘ revisei meu código e ‘ tenho o prazer de dizer que a grande maioria segue os princípios que você descreve. Sua explicação foi útil, porém, e me fez refletir e perceber que não ‘ apreciei que as instruções TRY CATCH do VB e do SQL Server sejam usadas apenas uma vez em cada procedimento (pensei que fossem um significa não ter que abstrair o código para torná-lo mais legível). Se quiser adicionar mais comentários sobre o procedimento ManageErrSource I ‘ m todos ouvidos …
  • @HarveyFrench I ‘ adicionarei mais alguns quando eu tiver a chance – hadn ‘ t olhei para este 😉 referenciar e usar a API VBIDE requer configurações de segurança especiais, o que não é legal. Eu ‘ passei a usar TypeName(Me) como uma fonte para erros personalizados em módulos de classe e a única maneira de um erro saber qual procedimento ocorreu em, é codificar o nome do procedimento em uma const local, de preferência não muito longe da assinatura do método ‘. Gosto da ideia da pilha de chamadas, mas uma desvantagem é que você precisa ” push ” e ” pop ” sempre que você entra / sai de um procedimento, caso contrário, torna-se uma mentira.
  • O código que recebi de fmsinc.com se espalha muito dos problemas que ‘ tenho tido.Eu ‘ d valorizo sua opinião. Veja aqui codereview.stackexchange.com/questions/94498/… Agradeço o seu tempo, pois isso está me motivando nozes.

Resposta

Ouça Mat “sMug , mas ele não abordou a situação em que você realmente sabe como se recuperar de um erro. Para completar, gostaria de cobrir isso.

Vejamos como faríamos algo assim no VB.Net primeiro.

Try foo = SomeMethodLikelyToThrowAnException Catch e As SomeException foo = someDefaultValue End Try " some more code 

A maneira idiomática de fazer isso no VB6 é ResumeNext. Anote isso, porque é a apenas vez que eu sempre direi isso “s direto para ResumeNext.

On Error Goto ErrHandler foo = SomeMethodLikelyToRaiseAnError " some more code CleanExit: " clean up resources Exit Sub ErrHandler: If Err.Number = ConstantValueForErrorWeExpected Then foo = someDefaultValue Resume Next End If Resume CleanExit "or re-raise error Exit Sub 

A forma alternativa é embutir essa lógica, que acho um pouco mais limpa e mais perto do Try...Catch idioma, mas pode ficar feio rapidamente se abusar dele.

On Error Resume Next foo = SomeMethodLikelyToRaiseAnError If Err.Number = ConstantValueForErrorWeExpected Then foo = someDefaultValue End If On Error Goto 0 

Qualquer um é um forma idiomática de lidar com os erros esperados, mas faça o que fizer. Não se preocupe com Resume Next até que você compreenda completamente o que ele faz e quando é apropriado . (Mais um aviso para futuros leitores do que para você. Você parece entender completamente o tratamento de erros em VB6. Talvez um pouco bem demais para o seu próprio bem.)

Comentários

  • Obrigado @RubberDuck por seus comentários úteis. Para ser honesto, acabo usando ” Em caso de erro, retomar próximo ” antes algumas chamadas de procedimento após r que normalmente existe um SELECT CASE que responde a qualquer erro levantado. O grande erro que percebo que estou cometendo é levantar uma exceção definida pelo usuário no subprocedimento para sinalizar situações que surgem (como o usuário solicitando o cancelamento do processamento). Acho que devo usar mais funções. Isso é uma indicação de que minha estrutura geral de código é ” não ideal ” / pobre e acho que preciso resolver isso. Obrigado.
  • Você ‘ acertou em cheio @HarveyFrench. As exceções são para comportamento excepcional , não para controlar o fluxo. Bem-vindo ao CR.
  • Eu ‘ d estaria muito interessado em suas opiniões sobre esta questão do SO: stackoverflow. com / questions / 31007009 / …
  • O código que recebi de fmsinc.com contorna muitos dos problemas que eu ‘ temos tido. Eu ‘ d valorizo sua opinião. Veja aqui codereview.stackexchange.com/questions/94498/…

Resposta

Esta resposta pretende simplificar o padrão Try / Catch para ser facilmente compreensível.

Isso não é muito diferente de tratamento de erros inline regular, exceto que pode pular várias linhas de uma vez, tratar um erro e então retomar a execução regular. Este é um padrão estruturado de forma muito limpa para lidar com um erro. O fluxo se move de forma muito limpa de cima para baixo; nenhum código espaguete aqui.

Tradicionalmente, o manipulador de erros é colocado na parte inferior. Mas a construção Try / Catch é tão elegante. É uma maneira muito estruturada de lidar com erros e é muito fácil de seguir. Esse padrão tenta reproduzir isso de uma maneira muito clara e concisa. O fluxo é muito consistente e não pula de um lugar para outro.

Sub InLineErrorHandling() "code without error handling BeginTry1: "activate inline error handler On Error GoTo ErrHandler1 "code block that may result in an error Dim a As String: a = "Abc" Dim c As Integer: c = a "type mismatch ErrHandler1: "handle the error If Err.Number <> 0 Then "the error handler is now active Debug.Print (Err.Description) End If "disable previous error handler (VERY IMPORTANT) On Error GoTo 0 "exit the error handler Resume EndTry1 EndTry1: "more code with or without error handling End Sub 

Fontes:

Gerenciado corretamente, funciona muito bem. É um padrão de fluxo muito limpo que pode ser reproduzido em qualquer lugar em que seja necessário.

Comentários

  • @D_Bester, Obrigado pelos links e pelo exemplo simples. Eu ‘ ainda estou aprendendo e achei seu feedback útil, mas você precisará adicionar um ” On Error Goto 0 ” após o ” no erro goto -1 “. Além disso, pensando bem, acho melhor usar Err.Clear em vez de ” On Error Goto -1 “, pois mostra mais claramente o que está acontecendo. Eu ‘ estou achando todo esse tratamento de erros no VBA uma espécie de arte negra.
  • @D_Bester. Pensando bem, seu código está bem se você quiser apenas dar uma mensagem ao usuário quando ocorrer um erro, mas e se quiser relançar o erro? Qual será um cenário muito comum. Considerar.Se seu código estava tentando pesquisar os detalhes de ‘ s de um cliente e não conseguiu ‘ obtê-los por um motivo INESPERADO. Você precisaria relançar o erro e deixar que o código que está usando seu código para fazer a pesquisa decida o que fazer.
  • @HarveyFrench Se você quiser relançar o erro, use ‘ Err.Raise ‘. Não há problema, presumindo que o código está bem estruturado e o tratamento de erros habilitado no código de chamada.
  • @HarveyFrench Err.Clear e On Error Goto -1 NÃO são equivalentes. Veja stackoverflow.com/a/30994055/2559297
  • Você ‘ está certo, eles estão não o mesmo desculpe. Mas acho que o código acima ainda precisa de On Error GoTo -1 substituído por Err.Clear, caso contrário, o ” ‘ mais código sem tratamento de erros ” irá para ErrHandler1 se ocorrer um erro.

Resposta

Sobre “CleanExit” e o tópico “Finalmente”.

A caneca de Mat “escreveu:

CleanExit é o ” finalmente ” parte, que é executada independentemente de um erro ter sido gerado ou não … a menos que você “esteja jogando novamente.


Tal situação poderia ocorrer, por exemplo, neste código de procedimento:

Abordagem de procedimento

Public Sub DoSomething() On Error GoTo CleanFail " Open any resource " Use the resource CleanExit: " Close/cleanup the resource Exit Sub CleanFail: Raise Err.Number Resume CleanExit End Sub 

Problema aqui : Se ocorrer algum erro no corpo dos métodos que deva ser gerado novamente em CleanFail, CleanExit não será executado um t tudo e, portanto, o recurso não pode “ser fechado corretamente.

Claro, você pode fechar o recurso também no próprio manipulador de erros, mas isso pode levar a vários fragmentos de código onde o tratamento de recursos será / tem a ser feito.


Minha sugestão é usar um objeto personalizado para cada necessidade de vinculação de recurso:

AnyResourceBindingClass

Private Sub Class_Initialize() "Or even use Mats "Create method" approach here instead. "Open/acquire the resource here End Sub Private Sub Class_Terminate() On Error GoTo CleanFail "Close/clean up the resource here properly CleanExit: Exit Sub CleanFail: MsgBox Err.Source & " : " & Err.Number & " : " & Err.Description Resume CleanExit End Sub Public Sub UseResource() "Do something with the resource End Sub 

Abordagem orientada a objetos

Public Sub DoSomething() On Error GoTo CleanFail " Use custom object which acquires the resource With New AnyResourceBindingClass .UseResource End With CleanExit: Exit Sub CleanFail: Raise Err.Number Resume CleanExit End Sub 

Oportunidade : Como o objeto personalizado ficará fora do escopo após o erro ser gerado, seu método Terminate será executado automaticamente, o que faz com que o recurso adquirido seja fechado / limpo de maneira adequada.

Uma necessidade a menos para um bloco “finalmente”.


Tratamento de erros no método Terminate

Na minha opinião, é dependente do contexto como um erro será tratado no método Terminate da classe personalizada. Talvez devesse ser registrado em algum lugar adicional ou até mesmo engolido?

Certamente isso é discutível.

Mas é essencial para habilite um manipulador de erros neste método, porque, até onde eu sei, qualquer erro não tratado neste método fará com que o VBA interrompa a execução e exiba sua caixa de mensagem de erro de tempo de execução padrão.

Resposta

Para esclarecer minha postagem anterior, a seguinte linha do código de HarveyFrench “:

RememberErrLine = Erl() 

não funcionará a menos que os números das linhas tenham sido adicionados a cada linha de código. Em vez de digitar manualmente os números das linhas, o que é muito tedioso, você pode usar uma ferramenta para adicionar os números das linhas automaticamente. existem algumas ferramentas que podem fazer isso, eu uso uma chamada CodeLiner.

Aqui está o código com os números das linhas, que permitirão que Erl() funcione com sucesso :

Option Compare Database Option Explicit Dim RememberErrNumber As Long Dim RememberErrDescription As String Dim RememberErrSource As String Dim RememberErrLine As Integer Private Sub RememberThenClearTheErrorObject() 10 11 On Error Resume Next 12 " For demo purposes 14 Debug.Print "ERROR RAISED" 15 Debug.Print Err.Number 16 Debug.Print Err.Description 17 Debug.Print Err.Source 18 Debug.Print " " 19 20 " This function has to be declared in the same scope as the variables it refers to 22 RememberErrNumber = Err.Number 23 RememberErrDescription = Err.Description 24 RememberErrSource = Err.Source 25 RememberErrLine = Erl() 26 " Note that the next line will reset the error object to 0, the variables above are used to remember the values " so that the same error can be re-raised 29 Err.Clear 30 " Err.Clear is used to clear the raised exception and set the err object to nothing (ie err.number to 0) " If Err.Clear has not be used, then the next "On Error GoTo ALabel" that is used in this or the procedure that called it " will actually NOT pass execution to the ALabel: label BUT the error is paseed to the procedure that called this procedure. " Using Err.Clear (or "On Error GoTo -1 ") gets around this and facilitates the whole TRY CATCH block scenario I am using there. 35 36 " For demo purposes 38 Debug.Print "ERROR RAISED is now 0 " 39 Debug.Print Err.Number 40 Debug.Print Err.Description 41 Debug.Print Err.Source 42 Debug.Print " " 43 " For demo purposes 45 Debug.Print "REMEMBERED AS" 46 Debug.Print RememberErrNumber 47 Debug.Print RememberErrDescription 48 Debug.Print RememberErrSource 49 Debug.Print " " 50 End Sub Private Sub ClearRememberedErrorObjectValues() 54 " This function has to be declared in the same scope as the variables it refers to 56 RememberErrNumber = 0 57 RememberErrDescription = "" 58 RememberErrSource = "" 59 RememberErrLine = 0 60 End Sub Sub ExampleOfTryCatchBlockInVBA() 67 68 On Error GoTo HandleError 69 70 " ----------------------------------------------------- " SubProcedure1 has the example of a multiple line TRY block with a block of code executed in the event of an error 73 74 SubProcedure1 75 76 77 78 Exit Sub 79 HandleError: 80 81 Select Case Err.Number 82 Case 0 " This shold never happen as this code is an error handler! " However if it does still allow the Err.raise to execute below. (In this case Err.raise will fail " and itself will raise an error "Invalid procedure call or argument" indicating that 0 cannot be used to raise and error! 86 87 Case 111111 " You might want to do special error handling for some predicted error numbers " perhaps resulting in a exit sub with no error or " perhaps using the Err.raise below 91 92 Case Else " Just the Err.raise below is used for all other errors 94 95 End Select 96 " " I include the procedure ManageErrSource as an exmple of how Err.Source can be used to maintain a call stack of procedure names " and store the name of the procedure that FIRST raised the error. " 101 Err.Raise Err.Number _ , ManageErrSource("MyModuleName", Err.Source, Erl(), "tsub1_RaisesProcedureNotFoundError") _ , Err.Number & "-" & Err.Description 104 " Note the next line never gets excuted, but I like to have resume in the code for when I am debugging. " (When a break is active, by moving the next executable line onto it, and using step over, it moves the exection point to the line that actually raised the error) 107 Resume 108 End Sub Sub SubProcedure1() 112 " ----------------------------------------------------- " Example of a multiple line TRY block with a Case statement used to CATCH the error 115 " " It is sometimes better to NOT use this technique but to put the code in it"s own procedure " (ie I refer to the code below that is surrounded by the tag #OWNSUB) . " However,sometimes using this technique makes code more readable or simpler! " 121 122 Dim i As Integer 123 " This line puts in place the defualt error handler found at the very foot of the procedure 125 On Error GoTo HandleError 126 127 " " Perhaps lots of statements and code here " 131 132 " First an example with comments 134 135 " ----------------------------------------------------- " TRY BLOCK START 138 " This next line causes execution to "jump" to the "catch" block in the event an error is detected. 140 On Error GoTo CatchBlock1_Start 141 " #OWNSUB 143 144 tsub_WillNotRaiseError_JustPrintsOk 145 146 If vbYes = MsgBox("1. Do you want to raise an error in the try block? - (PRESS CTRL+BREAK now then choose YES, try no later.)", vbYesNo) Then 147 i = 100 / 0 148 End If 149 " " Perhaps lots of statements and code here " 153 " #OWNSUB 155 " TRY BLOCK END " ----------------------------------------------------- 158 159 " ----------------------------------------------------- " CATCH BLOCK START 162 CatchBlock1_Start: 163 164 If Err.Number = 0 Then 165 On Error GoTo HandleError " Re-instates the procedure"s generic error handler " This is also done later, but I think putting it here reduces the likelyhood of a coder accidentally removing it. 168 169 Else 170 " WARNING: BE VERY CAREFUL with any code that is written here as " the "On Error GoTo CatchBlock1_Start" is still in effect and therefore any errors that get raised could goto this label " and cause and infinite loop. " NOTE that a replacement "On Error Goto" cannot be executed until Err.clear is used, otherwise the "On Error Goto" " will itself raise and error. " THEREFORE KEEP THE CODE HERE VERY SIMPLE! " RememberThenClearTheErrorObject should be the only code executed and this called procedure must be tight! 178 " This saves the details of the error in variables so that the "On Error GoTo HandleError" can be used " to determine how the next Err.Raise used below is handled (and also how any unexpected implicitly raised errors are handled) 181 RememberThenClearTheErrorObject 182 183 On Error GoTo HandleError "#THISLINE# 184 185 If vbYes = MsgBox("2. Do you want to raise an error in the erro handler? - (PRESS CTRL+BREAK now then try both YES and NO )", vbYesNo) Then 186 i = 100 / 0 187 End If 188 189 Select Case RememberErrNumber 190 Case 0: " No Error, do Nothing 191 192 Case 2517 193 Debug.Print "The coder has decided to just give a Warning: Procedure not found " & Err.Number & " - " & Err.Description 194 ClearRememberedErrorObjectValues " Not essential, but might save confusion if coding errors are made 195 196 Case Else " An unexepected error or perhaps an (user) error that needs re-raising occurred and should to be re-raised 198 " NOTE this is giving an example of what woudl happen if the CatchBlock1_ErrorElse is not used below 200 If vbYes = MsgBox("3. Do you want to raise an error in the ELSE error handler? CatchBlock1_ErrorElse *HAS NOT* been used? - (PRESS CTRL+BREAK now then try both YES and NO )", vbYesNo) Then 201 i = 100 / 0 202 End If 203 204 On Error GoTo CatchBlock1_ErrorElse 205 206 " SOME COMPLEX ERROR HANDLING CODE - typically error logging, email, text file, messages etc.. " Because the error objects values have been stored in variables, you can use " code here that might itself raise an error and CHANGE the values of the error object. " You might want to surround the code with the commented out CatchBlock1_ErrorElse lines " to ignore these errors and raise the remembered error. (or if calling a error handling module " just use on error resume next). " Without the CatchBlock1_ErrorElse lines any error raised in this "complex code" will be handled by the " active error handler which was set by the "On Error GoTo HandleError" tagged as "#THISLINE#" above. 215 216 If vbYes = MsgBox("4. Do you want to raise an error in the ELSE error handler when CatchBlock1_ErrorElse HAS been used? - (PRESS CTRL+BREAK now then try both YES and NO )", vbYesNo) Then 217 i = 100 / 0 218 End If 219 220 CatchBlock1_ErrorElse: 221 On Error GoTo HandleError " This line must be preceeded by an new "On error goto" for obvious reasons 223 Err.Raise RememberErrNumber, RememberErrSource, RememberErrDescription 224 225 End Select 226 227 On Error GoTo HandleError 228 229 End If " CATCH BLOCK END " ----------------------------------------------------- 232 On Error GoTo HandleError " Unnecessary but used to delimt the catch block 233 234 235 236 " " lots of code here perhaps " 240 241 242 243 " ----------------------------------------------------- " Example 2 " " In this example goto statements are used instead of the IF statement used in example 1 " and no explanitory comments are given (so you can see how simple it can look) " 250 " ----------------------------------------------------- " TRY BLOCK START 253 254 On Error GoTo CatchBlock2_Start 255 256 tsub_WillNotRaiseError_JustPrintsOk 257 258 If vbYes = MsgBox("Do you want to raise an error? - (PRESS CTRL+BREAK now then choose YES)", vbYesNo) Then 259 i = 100 / 0 260 End If 261 " " Perhaps lots of statements and code here " 265 " TRY BLOCK END " ----------------------------------------------------- 268 269 270 GoTo CatchBlock2_End: 271 CatchBlock2_Start: 272 273 RememberThenClearTheErrorObject 274 275 On Error GoTo HandleError 276 277 Select Case RememberErrNumber 278 Case 0: " No Error, do Nothing 279 280 Case 2517 281 Debug.Print "The coder has decided to just give a Warning: Procedure not found " & Err.Number & " - " & Err.Description 282 ClearRememberedErrorObjectValues " Not essential, but might save confusion if coding errors are made 283 284 Case Else " An unexepected error or perhaps an (user) error that needs re-raising occurred and should to be re-raised " In this case the unexpecetd erro will be handled by teh code that called this procedure " This line must be preceeded by an new "On error goto" for obvious reasons 288 Err.Raise RememberErrNumber, RememberErrSource, RememberErrDescription 289 290 End Select 291 292 On Error GoTo HandleError 293 294 End If 295 296 CatchBlock2_End: " CATCH BLOCK END " ----------------------------------------------------- 299 On Error GoTo HandleError " Unnecessary but used to delimt the catch block 300 301 302 303 " " Here you could add lots of lines of vba statements that use the generic error handling that is after the HandleError: label " " 308 " " You could of course, alway add more TRY CATCH blocks like the above " " 313 314 315 316 Exit Sub 317 HandleError: 318 319 Select Case Err.Number 320 Case 0 " This shold never happen as this code isan error handler! " However if it does still allow the Err.raise to execute below. (In this case Err.raise will fail " and itself will raise an error "Invalid procedure call or argument" indicating that 0 cannot be used to raise and error! 324 325 Case 111111 " You might watch to do special error handling for some predicted error numbers " perhaps exit sub " Perhaps using the Err.raise below 329 End Select 330 " ie Otherwise " " Note that I use the Err.Source to maintain a call stack of procedure names " 335 Err.Raise Err.Number _ , ManageErrSource("MyModuleName", Err.Source, Erl(), "tsub1_RaisesProcedureNotFoundError") _ , Err.Number & "-" & Err.Description 338 " Note the next line never gets excuted, but I like to have resume in the code for when I am debugging. " (By moving the next executable line onto it, and using step over, it moves the exection point to the line that actually raised the error) 341 Resume 342 End Sub Sub tsub_WillNotRaiseError_JustPrintsOk() 348 349 Static i As Integer 350 351 i = i + 1 352 353 Debug.Print "OK " & i 354 End Sub Public Function ManageErrSource(MyClassName As String, ErrSource As String, ErrLine As Integer, ProcedureName As String) As String 360 " This function would normally be in a global error handling module 362 " On Error GoTo err_ManageErrSource 364 365 Const cnstblnRecordCallStack As Boolean = True 366 367 Select Case ErrSource 368 369 Case Application.VBE.ActiveVBProject.Name 370 " Err.Source is set to this value when a VB statement raises and error. eg In Access by defualt it is set to "Database" 372 373 ManageErrSource = Application.VBE.ActiveVBProject.Name & " " & MyClassName & "." & ProcedureName & ":" & ErrLine 374 375 Case "" 376 " When writing code ouside of the error handling code, the coder can raise an error explicitly, often using a user error number. " ie by using err.raise MyUserErrorNumber, "", "My Error descirption". " The error raised by the coder will be handled by an error handler (typically at the foot of a procedure where it was raised), and " it is this handler that calls the ManageErrSource function changing the Err.Source from "" to a meaningful value. 381 382 ManageErrSource = Application.VBE.ActiveVBProject.Name & " " & MyClassName & "." & ProcedureName & ":" & ErrLine 383 384 Case Else 385 " This code is executed when ManageErrSource has already been called. The Err.Source will already have been set to hold the " Details of where the error occurred. " This option can be used to show the call stack, ie the names of the procdures that resulted in the prcedure with the error being called. 389 390 If cnstblnRecordCallStack Then 391 392 If InStr(1, ErrSource, ";") = 0 Then 393 ManageErrSource = ErrSource & ":: Called By: " 394 End If 395 ManageErrSource = ErrSource & ";" & ProcedureName & ":" & ErrLine 396 397 Else 398 ManageErrSource = ErrSource 399 400 End If 401 402 End Select 403 404 Exit Function 405 err_ManageErrSource: 406 Err.Raise Err.Number, "MyModuleName.err_ManageErrSource", Err.Description 407 Resume 408 End Function 

Comentários

  • Olá! Bem-vindo à revisão do código. Adicione mais contexto à sua resposta: explique por que sua sugestão vai melhorar o código do OP ‘ s ou talvez dê mais detalhes sobre o que você está tentando dizer.

Deixe uma resposta

O seu endereço de email não será publicado. Campos obrigatórios marcados com *