Python uses exceptions to signal that an error has occurred during the execution of your code. When an exception is raised, Python expects your code to handle it; otherwise, the program will terminate and display an error message. By properly handling exceptions, your application can recover from errors and continue running.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Using try and except
You can catch exceptions by wrapping the code that might cause an error in atry block and then providing one or more except blocks to handle specific exceptions. Consider the following example:
except block, the output is:
Handling Specific Exceptions
Many issues can occur in your program. Python lets you handle specific exceptions separately, providing targeted error messages for different error types. For example, when processing user input for a division operation, two common issues might arise:- The user might enter a non-integer value, which will cause a
ValueErrorwhen attempting to convert the input. - The user might enter zero, resulting in a
ZeroDivisionErrorduring division.

- If the user enters a valid integer that is not zero, the script successfully converts the input and performs the division.
- If the user enters zero, the
ZeroDivisionErrorblock is executed. - If the input cannot be converted to an integer, the
ValueErrorblock handles the error. - The final, unnamed
exceptblock catches any other unforeseen exceptions.
Always place the catch-all
except block at the end, after all specific exception handlers. Only one except block will catch an exception, and once an exception is handled, the remaining blocks will be ignored.Conclusion
Exception handling is a fundamental aspect of writing robust Python programs. By anticipating potential errors and handling them with specific and genericexcept blocks, your code can gracefully recover from unexpected issues. Now that you understand the basics of exception handling, it’s time to apply what you’ve learned and start refining your Python projects.
Happy coding!