excel vba - VBA Selective Error Handling -
how can trap particular errors in vba?
so far have been raising error same number in error handler( 1 don't want use particualr error) pass error handler, makes code bloated.
i wondering if there better way?
example of how have been doing far:
sub correct() on error goto correcthandler wrong correcthandler: 'some code handle out of range error (aka err.number 9) end sub sub wrong() dim badarray(1 1) variant on error goto wronghandler badarray(100) = 1 wronghandler: select case err.number case 9 err.raise 9 'code handle other errors end select end sub
typically other way around unless want have select case includes all possible errors can run into. typical use doing if error recoverable. if want in context of error handler (harder debug if isn't recoverable because lose information original error), i'd this:
sub correct() on error goto correcthandler wrong exit sub correcthandler: debug.print err.number end sub sub wrong() dim badarray(1 1) variant on error goto wronghandler dim integer = 1 / 0 badarray(100) = 1 exit sub wronghandler: if err.number = 11 debug.print "i can divide 0, no problem." resume next else err.raise err.number end if end sub
generally though, it's better handle these inline. turn off error handler, , test error number:
sub wrong() dim badarray(1 1) variant dim integer 'i think next line might fail reason... on error resume next = 1 / 0 if err.number = 11 debug.print "i can divide 0, no problem." elseif err.number <> 0 debug.print "what hell? didn't expect that." err.raise err.number end if 'turn error handling on. on error goto 0 badarray(100) = 1 end sub
in case, out of bounds assignment throws caught in calling function's handler.
Comments
Post a Comment