The try/except keywords
So far, we have reviewed and tested all our examples assuming the ideal condition, that is, the execution of the program will encounter no errors. On the contrary, applications fail from time to time either due to external factors, such as invalid user input and poor Internet connectivity, or program logic errors caused by the programmer. In such cases, we want the program to report/log the nature of error and either continue its execution or clean up resources before exiting the program. The try
/except
keywords offer a mechanism to trap an error that occurs during a program's execution and take remedial action. Because it is possible to trap and log an error in crucial parts of the code, the try
/except
keywords are especially useful while debugging an application.
Let's understand the try
/except
keywords by comparing two examples. Let's build a simple guessing game where the user is asked to guess a number between 0 and 9:
- A random number (between 0 and 9) is generated...