Python: ignoring errors?

Hey guys,
I’ve got a “scene selection” menu in the Zark game that makes scenes become available as you reach them. To do this, it first checks for a number of small files which tell it if certain scenes have been visited yet. The problem is, when one of these files has not been created yet, the script simply quits, and the menu is unable to function. Is there any way I could tell the script simply to ignore all errors and continue?

To elaborate a little more, each scene, when activated, generates a small text file with the number 1 in its body. The menu scans for each scene’s file and checks to see if it reads 1. If it does, the menu sets that scene’s availability boolean to 1. These booleans are set to False by default. If the corresponding file does not yet exist, I’d like the script just to skip over it and leave the bool set to False, and move onto the next one.

You can use Python’s exception handling functions to do this, something like:


try:
     # this will through an exception if the file can't be found
     file = open("filename")
except:
    # catch the exception here and deal with it, or in this case do nothing
    pass
else:
     # read the file here

Note: you can use this method to handle lots of potential errors that would normally cause a script to bail, allowing you to attempt to recover.

Piran

1 Like

Basically, put the “try” block before the code which may cause a crash. The “except” block tells the script what to do if an error happens in the try block. The “pass” is used because a line must be included for an except block: it does nothing except fix the syntax.

The “else” block in this case means “if there’s no error, do this”. I usually put such code right in the try block, however.

1 Like

Same here.

Is it just me, or is the else here completely redundant.

Is it just me, or is the else here completely redundant.

Potentially, but it’s there for completeness. While functionally there’s no difference, there are times when it’s useful purely from a readability point of view. Depending on how much code would appear in the “try” block, I sometimes seperate it out just to keep the exception handler with the actual code that throws the exception - but that’s just my preference.

Piran

Thanks! This works perfectly.