When Python runs your code, it might encounter an issue and raise an exception—a special type of object that signals an error occurred. If the exception isn’t handled, Python stops the program and displays an error message. Consider this example: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.
Use a try-except block to monitor code for errors. The code under the try block executes normally, but if an error occurs, the code in the corresponding except block takes over.
Try-Except: A Basic Example
You can handle exceptions using thetry and except keywords. In the example below, if an error arises in the try block, the program jumps to the except block:
Handling Specific Exceptions
Python allows you to handle specific types of errors individually. Among the common error types are:- ZeroDivisionError
- ValueError
- TypeError
- SystemError
- AssertionError
- AttributeError
- IndexError
- KeyError
- IndentationError

| Scenario | Expected Exception |
|---|---|
| User enters a non-numeric string | ValueError |
| User enters zero | ZeroDivisionError |
except block without a specified exception type should always come last to catch any other unforeseen errors.
Always handle specific exceptions before using a generic exception block. This practice improves code readability and error handling precision.