excel - Check errors before function call or within function? -


i curious know considered best method check errors before running function. best make check before function called or within function itself?

for example, simplified version of i'm working on involves click subroutine:

private sub mybutton1_click()     j = 1 3         createchart sheets(j)     next j end sub 

where function calls defined so:

function createchart(sht worksheet) boolean     set chtobj = sht.chartobjects.add(40, 40, 600, 300)     set cht = chtobj.chart ... end function 

i dealing code multiple modules , many situations checks need performed before function can run. appropriate put check within loop in click sub routine, like:

if doessheetexist(sheets(j)) createchart(sheets(j)) 

or best put within function like:

if not doessheetexist(sht) createchart = false: exit function 

currently have little bit of each practice scattered throughout code , clean up. best run check outside function or within?

i dealing code multiple modules , many situations checks need performed before function can run. appropriate put check within loop in click sub routine, like:

generally avoid repeating same check in main code if going each.

in situation have 4 checks, , know issue causing problem when function fails means of msgbox, leave checks outside of loops in main code 1 notification appears. there way have checks within functions report issues once?

it sounds have handful of checks same each createchart method. like:

sub mainsub()     if validatecreatechart         createchart     end if end sub  sub createchart()     on error goto errhandler     'do stuff     exit sub     errhandler:         msgbox  "unexpected error: " & err.description end sub  function validatecreatechart() boolean       if conditionone         validatecreatechart = false         msgbox "error condition 1"         exit function     end if       if conditiontwo         validatecreatechart = false         msgbox "error condition 2"         exit function     end if      'etc  end function 

you don't want have logic errors/prompts scattered everywhere. if doing same checks , have same error prompts each of them.

don't leave sub/function without error handling or find regretting when "this never happen" circumstance happens.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -