Skip to main content
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:
In this case, Python raises a NameError because the variable “naem” does not exist. Instead of crashing immediately, you can catch and handle exceptions so that the program continues executing.
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 the try and except keywords. In the example below, if an error arises in the try block, the program jumps to the except block:
The output of this code is:
Since the exception was caught, Python exits the try-except block and continues with the rest of the program.

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
The image lists various Python error types, including ZeroDivisionError, ValueError, TypeError, SystemError, AssertionError, AttributeError, IndexError, KeyError, IndentationError, and others.
Suppose you ask a user to input a number and try to compute its reciprocal. Two issues may occur: Here’s how you can manage these specific exceptions using multiple except blocks:
When a ValueError occurs (for example, if the user inputs a non-integer), the corresponding except block is executed. Likewise, entering zero triggers the ZeroDivisionError block. Note that any generic 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.
That concludes our article on Python errors and exceptions. Now, it’s time to put this knowledge into practice and enhance your Python programming skills!

Watch Video