Exception handling

Exception handling

Exception handling is the process of coding in solutions to possible errors that would otherwise crash your program.

The sort of errors that might accidentally crash your program include:
* ZeroDivisionError: Trying to divide a number by zero
* ValueError: Trying to convert a string to integer
* FileNotFoundError: Trying to read a file that doesn't exist
* TypeError: Trying to use a string in a calculation

Try...except

The way to overcome exception errors is to use a try except statement. This tells the program to try a line of code and allows us to specify what to do if that code produces an error.



Zero division error

By excepting a zero division error we can prevent our program from crashing if it were accidentally asked to dviide by zero.



Value errors

By excepting value errors we can prevent the program from crashing if it encounters an unexpected data tye.



File not found error

By excepting a file not found error we can prevent the program from crashing if it attempts to open a non existent file such as loading a wrongly named save game.



Type errors

By excepting type errors we can avoid the rogram crashing if we actually try to perform an action with the wrong data type.



Else and finally

You can also add else and finally blocks to a try except statement. Code in the else block will run if there is no exception. Code in the finally block will be run regardless of whether there is an exception or not.



Knowledge check


Questions:
Correct:

Question text


© All materials created by and copyright S.Goff