What is exception handling?
Exception handling is a mechanism to handle the exceptions that are generated by runtime errors.
Example
Consider the following program:
If we were to run this program using the values 1 and 2 as input. The output from the program would be:
However, if we were to run this program using the values 1 and tree as input. The output from the program would be:
Notice how this execution generated an exception on line 4.
Line 4 of the program contains the following line of code:
We are attempting to cast the value in the variable num2 to an int.
However, we executed the program we inputted the value tree which was stored in num2. We cannot cast this value to an int, hence the ValueError exception.
We can use exception handling to catch this exception, without generating a runtime error and crashing the program.
Exception handling in Python
We use a TRY...CATCH structure to accomplish this.
How this works
- The try phase - try to execute a block of code
- if no exception is generated
- continue with the program
- The catch phase - if an exception is generated
- catch the exception (so that a runtime error does not occur)
- do something (usually this will be something to remedy the error)
- continue with the program
The program using exception handling
This time if we were to run this program using the values 1 and tree as input. The output from the program would be: