Exceptions


By HyperNeutrino
Written 19 days ago

Exceptions are the errors thrown by the program when you perform invalid actions, like dividing by zero. Normally, they will cause your program to crash; however, you can catch these errors and process them manually. The basic syntax is as follows:

try:
    run_some_code()
except:
    if_it_fails()
finally:
    closing_statements()

In the try block, the code will be attempted to be run. If nothing bad happens, then the except block does not take effect. If the try block errors, then the program will direct to the except block.

The finally block will almost always run.

You can also use except ErrorName to catch specific types; for example, except ValueError for parsing numbers.

Finally, you can use except ErrorName as e to catch the error and store it in the variable e. This lets you output things related to e, such as print(e), but for now, you don't need to know what functions exist to process e.