Poniższy kod jest dość oczywisty: po prostu skopiuj i wklej wszystko do modułu i uruchom go , zawiera kilka przypadków użycia i wiele objaśniających komentarzy w tekście. (To działa, ale interesuje mnie, co myślą o tym inni ludzie i wszelkie sugestie, jakie mógłbyś przedstawić).

Najważniejsze fakty, które należy sobie uświadomić, to:

  1. Kiedy używasz w przypadku błędu goto Label1, procedura wchodzi w stan „Ja” obsługuję błąd ”, ponieważ został zgłoszony wyjątek. W tym stanie, jeśli zostanie wykonana inna instrukcja „On Error Goto” etykieta2, NIE przejdzie ona do etykiety2, ale zgłosi błąd i zostanie przekazany do kodu, który wywołał procedurę.

  2. Możesz zatrzymać procedurę w stanie „Obsługuję błąd”, usuwając wyjątek (ustawiając err na zero, aby właściwość err.number zmienił się na 0), używając

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

(UWAGA, że On Error Goto 0 różni się od powyższego)

Należy również zauważyć, że Err.Clear resetuje go do zera, ale w rzeczywistości jest to równoważne z:

On Error Goto -1 On Error Goto 0 

tzn. Err.Clear usuwa „On Error Goto”, który jest obecnie na miejscu. Dlatego najlepiej jest używać:

On Error Goto -1 

jako Err.clear Często trzeba napisz

Err.Clear On Error Goto MyErrorHandlerLabel 

Używam powyższych technik z różnymi etykietami, aby zasymulować czasami użyteczną funkcjonalność, jaką dają bloki Visual Basic TRY CATCH, które moim zdaniem mają swoje miejsce w piśmie czytelny kod.

Wprawdzie ta technika tworzy kilka wierszy kodu więcej niż ładna instrukcja VB try catch, ale nie jest zbyt niechlujna i dość łatwa do zdobycia r się rozejrzyj.

PS. Interesująca może być również procedura ManageErrSource, która sprawia, że właściwość Err.Source przechowuje procedurę, w której wystąpił błąd.

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 

Komentarze

  • Tylko dwa komentarze: 1 Dlaczego, u licha, miałbyś to wykorzystać? 2 On Error Goto -1
  • Try / catch można również emulować, opakowując odpowiedni kod tagami On Error Resume Next i i sprawdzając Err.Number. Powyższe jest nieco trudne do zrozumienia, ma trochę spaghetti struktury ..
  • Dzięki Rory, ja ' zmieniłem to. Użyłbyś tego lub tego samego powodu, dla którego ktoś użyłby instrukcji TRY CATCH w VB lub SQL Server. tzn. pozwala na inną strukturę kodu. tzn. możesz użyć tego samego programu obsługi błędów dla wielu wierszy kodu bez konieczności umieszczania wierszy w ich własnej procedurze.
  • Loannis. tak, ' robiłem to w przeszłości, dla pojedynczych linii kodu, które wymagają obsługi błędów. To znaczy jedna linia kodu ma jedną obsługę błędów. TRY CATCH pozwala na osadzenie bloku kodu (z wieloma wierszami) w procedurze z własnym ' programem obsługi błędów. Często używam TRY CATCH w SQL Server, a ponieważ ' jest dostępny również w VB, musi służyć do jakiegoś ogólnie użytecznego celu. Trzeba przyznać, że ta wersja jest trochę niechlujna.
  • @Loannis A co, jeśli chcesz pominąć wiele linii, gdy pojawi się błąd. Zobacz moją odpowiedź na uproszczony przykład. Oczywiście możesz to również zrobić przy regularnej obsłudze błędów.

Odpowiedź

Problem polega na tym, że błędy w czasie wykonywania VBA nie są wyjątkami , a obsługa błędów w VBA ma bardzo niewiele wspólnego z obsługą wyjątków.

RememberErrLine = Erl() 

Erl jest ukrytym elementem modułu VBA.Information z jakiegoś powodu – zwraca 0, chyba że błąd wystąpił w numerowanej linii. A jeśli „używasz numerów linii w języku VBA, mieszkasz w jaskini od 25 lat i prawdopodobnie używasz instrukcji GoSub zamiast pisania procedur. Numery linii są obsługiwane ze względu na starsze / starsze wersje , ponieważ kod napisany w latach 80-tych ich wymagał .

Podoba mi się, jak sam to powiedziałeś:

" THEREFORE KEEP THE CODE HERE VERY SIMPLE! 

.. ale dlaczego nie jest to zastosowane do reszty kodu? Bez obrazy, ale to jest logika spaghetti, napisana w procedurach, które wyraźnie i bezwstydnie naruszają Zasada pojedynczej odpowiedzialności . Żaden kod zgodny z SRP nie wymagałby nigdy dwóch takich ” try-catch ” bloków.

To pachnie:

Case 0: " No Error, do Nothing 

Oznacza to jedną z dwóch rzeczy: albo masz kod obsługi błędów, który działa w kontekstach innych niż błędy, lub masz martwy kod, który należy usunąć.

To pachnie śmierdzi :

GoTo CatchBlock2_End: CatchBlock2_Start: 

Po pierwsze, ac olon (:), który nie określa etykiety wiersza , jest separatorem instrukcji .Okazuje się, że nowa linia jest również ” separatorem instrukcji „, więc dwukropek na końcu GoTo CatchBlock2_End jest całkowicie bezużyteczny i zagmatwany, , zwłaszcza biorąc pod uwagę poziom wcięć w instrukcji GoTo .

A propos GoTo

Neil Stephenson uważa, że fajnie jest nazywać jego wytwórnie„ dengo ”

Nie podoba mi się, jak muszę przeskakiwać między etykietami, aby śledzić kod. IMO to jest niechlujne i niepotrzebnie spaghetti.


Dobra, smartypants . Jak więc można porządnie obsłużyć błędy w VBA?

1. Przede wszystkim pisz czysty kod.

Stosuj się do najlepszych praktyk i pisz małe procedury, które robią jedną rzecz i robią to dobrze.

2. Napisz kod zorientowany obiektowo.

Abstrakcja i hermetyzacja to dwa z 4 filarów OOP , i „są w pełni obsługiwane w VBA. Polimorfizm też jest pewną opcją; wykluczone jest tylko właściwe dziedziczenie , ale to nie przeszkadza w abstrakcjonowaniu pojęć w moduły klas i tworzenie instancji wyspecjalizowanych obiektów.

Kod proceduralny napisany w standardowych modułach (.bas) powinien być drobnymi, małymi metodami publicznymi (makro ” haki „), które tworzą obiekty wymagane do uruchomienia funkcji.

Jak to się ma, nawet zdalnie, do właściwej obsługi błędów?

3. Przyjmij idiomatyczną obsługę błędów, nie walcz z tym.

Biorąc pod uwagę kod, który jest zgodny z powyższymi punktami, nie ma powodu, aby nie implementować obsługi błędów idiomatyczny sposób 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 

Ten wzorzec jest analogiczny do ” try-catch-last ” w następujący sposób:

  • Treść to ” try ” część, robi to, co mówi nazwa metody i nic więcej
  • CleanFail to ” catch ” część, działająca tylko w przypadku zgłoszenia błędu
  • CleanExit to ” w końcu ” część, działająca niezależnie od tego, czy zgłoszony został błąd … chyba że „ponownie przerzucasz . Ale jeśli chcesz wyświetlić błąd dla kodu wywołującego do obsłużenia, nie powinieneś mieć dużo czyszczenia c ode do wykonania i powinieneś mieć bardzo, bardzo dobry powód, aby to zrobić.

Jeśli podprogram obsługi błędów może spowodować błąd, oznacza to, że nie stosujesz się do SRP. Na przykład zapisywanie do pliku dziennika jest samo w sobie problemem, który powinien zostać wyabstrahowany do jakiegoś Logger obiektu, który żyje, aby radzić sobie z problemami związanymi z rejestrowaniem i ujawnia metody obsługujące własne błędy . Kod procedury obsługi błędów powinien być trywialny.

Komentarze

  • Dzięki @mat ' zadowolony za wzięcie czas na dodanie komentarzy, które naprawdę mi pomogły. ' jestem gotowy na gwałtowną, ale humorystyczną krytykę. ' przeglądałem mój kod i ' z przyjemnością stwierdzam, że zdecydowana większość przestrzega przedstawionych przez Ciebie zasad. Twoje wyjaśnienie było jednak przydatne i sprawiło, że zastanowiłem się i uświadomiłem sobie, że nie ' doceniam, że instrukcje VB i SQL Server TRY CATCH są używane tylko raz w każdej procedurze (myślałem, że to oznacza brak konieczności tworzenia abstrakcyjnego kodu, aby był bardziej czytelny). Jeśli masz ochotę dodać więcej komentarzy na temat procedury ManageErrSource, mam ' wszystkie uszy …
  • @HarveyFrench I ' dodam trochę więcej, kiedy będę miał okazję – nie ' nie spojrzałem na to 😉 odwoływanie się i używanie VBIDE API wymaga specjalnych ustawień bezpieczeństwa, co nie jest fajne. ' zacząłem używać TypeName(Me) jako źródła niestandardowych błędów w modułach klas i jedynego sposobu, aby dowiedzieć się, jaka procedura jest dla błędu miało to miejsce w, polega na zakodowaniu na stałe nazwy procedury w lokalnej sygnaturze const, najlepiej niezbyt daleko od metody '. Podoba mi się pomysł stosu wywołań, ale jedną wadą jest to, że musisz konsekwentnie ” push ” i ” pop ” za każdym razem, gdy wchodzisz / wychodzisz z procedury, w przeciwnym razie staje się to kłamstwem.
  • Kod, który otrzymałem z fmsinc.com, często się kręci z problemów, które ' miałem.' c cenię Twoją opinię. Zobacz tutaj codereview.stackexchange.com/questions/94498/… Doceniam Twój czas, bo to mnie napędza orzechy.

Odpowiedź

Listen to Mat „sMug , ale nie opisał sytuacji, w której tak naprawdę wiesz, jak naprawić błąd. Dla kompletności chciałbym to omówić.

Spójrzmy najpierw, jak zrobilibyśmy coś takiego w VB.Net.

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

Idiomatycznym sposobem na zrobienie tego w VB6 jest ResumeNext. Zapisz to, ponieważ to tylko czas, kiedy kiedykolwiek to powiem prawo do 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 

Alternatywnym sposobem jest wbudowanie tej logiki, która moim zdaniem jest nieco czystsza i bliżej idiomu Try...Catch, ale może stać się brzydki, jeśli go nadużyjesz.

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

Albo idiomatyczny sposób radzenia sobie z oczekiwanymi błędami, ale cokolwiek robisz. Nie przejmuj się Resume Next, dopóki nie całkowicie zrozumiesz, co robi i kiedy jest to właściwe . (Bardziej ostrzeżenie dla przyszłych czytelników niż dla ciebie. Wydaje się, że dobrze rozumiesz obsługę błędów w VB6. Być może trochę za dobrze dla twojego własnego dobra).

Komentarze

  • Dzięki @RubberDuck za przydatne komentarze. Szczerze mówiąc, używam ” W przypadku błędu wznów następny ” przed kilka wywołań procedur po zakończeniu r, w którym zwykle występuje SELECT CASE, który odpowiada na każdy zgłoszony błąd. Zdaję sobie sprawę, że popełniam wielki błąd polegający na tym, że zgłaszam wyjątek zdefiniowany przez użytkownika w procedurze podrzędnej, aby oznaczyć powstające sytuacje (np. Użytkownik żądający anulowania przetwarzania). Myślę, że powinienem częściej używać funkcji. Wskazuje to, że moja ogólna struktura kodu jest ” nieidealna ” / słaba i myślę i muszę się tym zająć. Dzięki.
  • ' trafiłeś w świetny punkt @HarveyFrench. Wyjątki dotyczą wyjątkowego zachowania, a nie kontroli przepływu. Witamy w CR.
  • I ' bym był bardzo zainteresowany twoimi opiniami na to pytanie SO: stackoverflow. com / questions / 31007009 / …
  • Kod, który otrzymałem z fmsinc.com, rozwiązuje wiele problemów, które ' już. ' c cenię Twoją opinię. Zobacz tutaj codereview.stackexchange.com/questions/94498/…

Odpowiedź

Ta odpowiedź ma na celu uproszczenie wzorca Try / Catch, aby był łatwy do zrozumienia.

Nie różni się to zbytnio od regularna wbudowana obsługa błędów, z wyjątkiem tego, że może pomijać wiele wierszy jednocześnie, obsłużyć błąd, a następnie wznowić zwykłe wykonywanie. Jest to bardzo przejrzysty wzorzec obsługi błędu. Przepływ przebiega bardzo czysto od góry do dołu; brak kodu spaghetti.

Tradycyjnie procedura obsługi błędów jest umieszczona na dole. Ale konstrukcja Try / Catch jest tak elegancka. Jest to bardzo zorganizowany sposób radzenia sobie z błędami i bardzo łatwy do naśladowania. Ten wzorzec próbuje to odtworzyć w bardzo przejrzysty i zwięzły sposób. Przepływ jest bardzo spójny i nie przeskakuje z miejsca na miejsce.

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 

Źródła:

Prawidłowo zarządzany to działa całkiem nieźle. Jest to bardzo czysty, płynny wzór, który można odtworzyć wszędzie tam, gdzie jest potrzebny.

Komentarze

  • @D_Bester, Dziękuję za linki i prosty przykład. ' Wciąż się uczę i uważam, że Twoja opinia jest przydatna, jednak będziesz musiał dodać ” Błąd Idź do 0 ” po ” przy błędzie goto -1 „. Po zastanowieniu myślę, że lepiej jest użyć Err.Clear zamiast ” Przy błędzie Goto -1 „, ponieważ wyraźniej pokazuje, co dzieje się. ' Uważam, że cała ta obsługa błędów w VBA jest trochę czarną sztuką.
  • @D_Bester. Po zastanowieniu się, kod jest w porządku, jeśli wszystko, co chcesz przekazać użytkownikowi komunikat, gdy wystąpi błąd, ale co, jeśli chcesz ponownie zgłosić błąd? Co będzie bardzo powszechnym scenariuszem. Rozważać.Jeśli kod próbował wyszukać szczegóły klienta ' i nie mógł go ' uzyskać z NIEOCZEKIWANEGO powodu. Musiałbyś ponownie zgłosić błąd i pozwolić, aby kod, który używa Twojego kodu do wyszukiwania, zdecydował, co zrobić.
  • @HarveyFrench Jeśli chcesz ponownie zgłosić błąd, po prostu użyj ' Err.Raise '. Nie ma problemu, zakładając, że kod ma dobrą strukturę, a w kodzie wywołującym jest włączona obsługa błędów.
  • @HarveyFrench Err.Clear i On Error Goto -1 NIE są równoważne. Zobacz stackoverflow.com/a/30994055/2559297
  • Ty ' masz rację nie to samo przepraszam. Myślę jednak, że powyższy kod nadal wymaga zastąpienia On Error GoTo -1 przez Err.Clear, w przeciwnym razie ” ' więcej kodu bez obsługi błędów ” przejdzie do ErrHandler1, jeśli wystąpi błąd.

Odpowiedz

Odnośnie tematu „CleanExit” i „Wreszcie”.

Kubek Mat ”napisał:

CleanExit to ” w końcu ” część, która działa niezależnie od tego, czy został zgłoszony błąd, czy nie … chyba że „ponownie wrzucisz”.


Taka sytuacja może wystąpić na przykład w tym kodzie proceduralnym:

Podejście proceduralne

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 

Problem tutaj : Jeśli w treści metody wystąpi jakikolwiek błąd, który musi zostać ponownie wywołany w CleanFail, CleanExit nie zostanie wykonany t all i dlatego zasobu nie można poprawnie zamknąć.

Oczywiście, możesz zamknąć zasób również w samym module obsługi błędów, ale może to prowadzić do wielu fragmentów kodu, w których obsługa zasobów będzie / ma do zrobienia.


Moją sugestią jest użycie niestandardowego obiektu dla każdej konieczności powiązania zasobów:

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 

Podejście obiektowe

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 

Okazja : Ponieważ obiekt niestandardowy będzie poza zakresem po wystąpieniu błędu, jego metoda Terminate zostanie wykonana automatycznie, co spowoduje, że pobrany zasób zostanie poprawnie zamknięty / wyczyszczony.

Jedno wymaganie mniej dla blok „na końcu”.


Obsługa błędów w metodzie Terminate

Moim zdaniem jest to zależne od kontekstu jak błąd zostanie obsłużony w metodzie Terminate klasy niestandardowej. Może powinno być gdzieś dodatkowo rejestrowane lub w ogóle połknięte?

Z pewnością jest to do omówienia.

Ale jest to włącz obsługę błędów w tej metodzie, ponieważ, o ile wiem, każdy nieobsłużony błąd w tej metodzie spowoduje przerwanie wykonywania przez VBA i wyświetlenie standardowego okna komunikatu o błędzie w czasie wykonywania.

Odpowiedź

Aby wyjaśnić mój poprzedni post, poniższy wiersz z kodu HarveyFrench:

RememberErrLine = Erl() 

nie będzie działać, jeśli numery wierszy nie zostaną dodane do każdego wiersza kodu. Zamiast ręcznie wpisywać numery wierszy, co jest zbyt żmudne, możesz użyć narzędzia do automatycznego dodawania numerów wierszy. jest kilka narzędzi, które mogą to zrobić, ja używam takiego o nazwie CodeLiner.

Oto kod z numerami wierszy, który pozwoli Erl() działać pomyślnie :

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 

Komentarze

  • Cześć! Witamy w przeglądzie kodu. Dodaj więcej kontekstu do swojej odpowiedzi: wyjaśnij, dlaczego Twoja sugestia poprawi kod OP ' lub może bardziej szczegółowo opisz, co próbujesz powiedzieć.

Dodaj komentarz

Twój adres email nie zostanie opublikowany. Pola, których wypełnienie jest wymagane, są oznaczone symbolem *