how run a function when a error happen?

since when you have a error , the error it self can due other errors , and if you not press esc quikly you not see the real error in the consolle.

so , i want to stop the game engine at the first error, running endGame():


import bge

if errorHappen: #how replace this line?
    bge.logic.endGame()

def buggyCode(cont): #entry point
    1 = error


it seem that you have to write a class , but not know how write it exactly .

help?

You want to use a try except block. The try defines code that is expected (allowed) to raise errors, and the except is run when the error occurs. You can define the types of error that are allowed to happen. Make sure that you need to catch the error though - errors (exceptions) are supposed to be infrequent else you have a design flaw

Sent from my Nexus 7 using Tapatalk 4

this is what i actually do ,but it is andly only in some cases
what i mean is another thing , that should “cover” all module (or i guess) or i’m wrong?

i see in some script something as :


class Exception(Exception):
    # other code that not recall

is possible?

You seem to be on the right track. I usually use something like this to stop the game immediately when an unexpected error occurs.

try:
    # call your code here
    myClass.main()
except: # catch all exceptions
    # end the game and re-raise the exception
    bge.logic.endGame()
    raise

If you have separate modules, you’ll have to either do something like this in each of them or just have it once in a central script that calls each module.

ah, this of “raise” to see anyway the error is new , good
PS: the other module not, will be sufficient the current module

You should refactor your program to avoid the error condition.

Exceptions should be used for exceptional circumstances.

I think the whole purpose of doing this is to make it easier to find and rectify such errors. Otherwise an error may happen on only one frame and you may not notice it, or the error that occurred may trigger other errors to occur every frame, making it difficult to identify the original error as it may be pushed out of the console buffer before you end the game.

I recommend to use this method ONLY when you investigate on such difficult errors.
So better remove it after you fixed the problematic situation.

If you forgot to remove it, the game might stop because of some silly errors, that could be handled otherwise.

Check out “sys.execpthook” this is the exception handler that process all uncaught exceptions. I understand your pain with the “exception throwup” that often buries the real cause.

I’ve considered creating a handler that that would attempt to suppress repeated exceptions so I could see a list of the unique exceptions that happened during the run.

thanks
maybe i can see for other, but try/except+raise work well
(without raise , running two times the error do a print a bit dirty)