Python Exception Handling Tutorial And Examples

1. What Is an Exception In Python?

  1. An exception in Python is an error that occurs during the execution of a program.
  2. It is usually caused by an unexpected event, such as a wrong input or a bug in the code.
  3. When an exception is encountered, the program stops and an exception object is created.
  4. This object contains information about the error, such as the type of error and the line of code where the error occurred.
  5. Exceptions can be handled using try-except blocks, which allow the program to continue running even if an exception is encountered.
  6. For example, a Python syntax error can lead to an exception being raised.
  7. If you try to use a variable that has not been defined, you will get a NameError exception.
  8. Another example is if you try to use a function that does not exist, you will get a NameError exception.
  9. Additionally, if you try to use an operator on incompatible types, you will get a TypeError exception.

2. Python Exception Types.

Python has a variety of built-in exception types that can be used to handle errors. These include:

  1. SyntaxError: Raised when the code is syntactically incorrect.
  2. NameError: Raised when a name is not found in the local or global scope.
  3. TypeError: Raised when an operation or function is applied to an object of an incorrect type.
  4. ValueError: Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value.
  5. IndexError: Raised when a sequence subscript is out of range.
  6. KeyError: Raised when a dictionary key is not found.
  7. AttributeError: Raised when an attribute reference or assignment fails.
  8. ImportError: Raised when an imported module is not found.
  9. IOError: Raised when an input/output operation fails.
  10. ZeroDivisionError: Raised when the second argument of a division or modulo operation is zero.
  11. MemoryError: Raised when an operation runs out of memory.
  12. SystemError: Raised when the interpreter detects an internal error.
  13. SystemExit: Raised when the sys.exit() function is called.
  14. KeyboardInterrupt: Raised when the user hits the interrupt key (Ctrl+C).
  15. RuntimeError: Raised when an error occurs that does not fall into any of the other categories.
  16. NotImplementedError: Raised when an abstract method that needs to be implemented in a subclass is not actually implemented.
  17. IndentationError: Raised when there is an incorrect indentation.
  18. TabError: Raised when there is an incorrect tab.
  19. SystemExit: Raised when the sys.exit() function is called.
  20. StopIteration: Raised when the next() method of an iterator does not point to any object.
  21. NotImplementedError: Raised when an abstract method that needs to be implemented in a subclass is not actually implemented.
  22. IndentationError: Raised when there is an incorrect indentation.
  23. TabError: Raised when there is an incorrect tab.
  24. SystemError: Raised when the interpreter detects an internal error.
  25. UnicodeError: Raised when a Unicode-related encoding or decoding error occurs.
  26. UnboundLocalError: Raised when a reference is made to a local variable in a function or method, but no value has been assigned to it.
  27. AssertionError: Raised when an assert statement fails.
  28. ArithmeticError: Raised when an error occurs in numeric calculations.
  29. FloatingPointError: Raised when a floating point operation fails.

3. How To Deal With Python Exception?

  1. To treat Python exceptions, you should use the try and except statements.
  2. The try statement allows you to test a block of code for errors.
  3. The except statement allows you to handle the error.
  4. You can also use the finally statement to execute code, regardless of the result of the try– and except statements.
  5. Here is an example of using the try and except statements to handle a Python exception.
    try:
        # code that may cause an exception
    except ExceptionType as e:
        # code to handle the exception
        print(e)
  6. Here is an example of using the try, except, and finally statements to handle a Python exception.
    try:
        # code that may cause an exception
    except ExceptionType as e:
        # code to handle the exception
        print(e)
    finally:
        # code that will always be executed
        print("This code will always be executed")
  7. Here is an example of a general Python exception, it can be used to catch any uncached python exception.
    try:
        # code that may cause an exception
    except Exception as e:
        # code to handle the exception
        print(e)
  8. Here is an example of using multiple branches to handle multiple Python exceptions.
    try:
        # code that may cause an exception
    except ExceptionType1 as e1:
        # code to handle ExceptionType1
        print(e1)
    except ExceptionType2 as e2:
        # code to handle ExceptionType2
        print(e2)
  9. Here is an example of using the raise statement to raise a Python exception.
    try:
        # code that may cause an exception
        raise Exception("This is an example of a raised exception")
    except Exception as e:
        # code to handle the exception
        print(e)
  10. Here is an example of creating a custom Python exception. You can read the article How To Use User Defined Exception In Python to learn more.
    class CustomException(Exception):
        def __init__(self, message):
            self.message = message
    try:
        # code that may cause an exception
        raise CustomException("This is an example of a custom exception")
    except CustomException as e:
        # code to handle the exception
        print(e.message)
  11. In Python, the assert statement is used to check if a condition is true, and if not, raise an AssertionError exception.
  12. It is used for debugging purposes to make sure that the code is behaving as expected.
  13. Here is an example of using the assert statement in Python.
    >>> x = 5
    >>> assert x > 0, "x must be greater than 0"
    >>>
    >>> x = -1
    >>> assert x > 0, "x must be greater than 0"
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AssertionError: x must be greater than 0

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.