1. What Is an Exception In Python?
- An exception in Python is an error that occurs during the execution of a program.
- It is usually caused by an unexpected event, such as a wrong input or a bug in the code.
- When an exception is encountered, the program stops and an exception object is created.
- This object contains information about the error, such as the type of error and the line of code where the error occurred.
- Exceptions can be handled using try-except blocks, which allow the program to continue running even if an exception is encountered.
- For example, a Python syntax error can lead to an exception being raised.
- If you try to use a variable that has not been defined, you will get a NameError exception.
- Another example is if you try to use a function that does not exist, you will get a NameError exception.
- 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:
- SyntaxError: Raised when the code is syntactically incorrect.
- NameError: Raised when a name is not found in the local or global scope.
- TypeError: Raised when an operation or function is applied to an object of an incorrect type.
- ValueError: Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value.
- IndexError: Raised when a sequence subscript is out of range.
- KeyError: Raised when a dictionary key is not found.
- AttributeError: Raised when an attribute reference or assignment fails.
- ImportError: Raised when an imported module is not found.
- IOError: Raised when an input/output operation fails.
- ZeroDivisionError: Raised when the second argument of a division or modulo operation is zero.
- MemoryError: Raised when an operation runs out of memory.
- SystemError: Raised when the interpreter detects an internal error.
- SystemExit: Raised when the sys.exit() function is called.
- KeyboardInterrupt: Raised when the user hits the interrupt key (Ctrl+C).
- RuntimeError: Raised when an error occurs that does not fall into any of the other categories.
- NotImplementedError: Raised when an abstract method that needs to be implemented in a subclass is not actually implemented.
- IndentationError: Raised when there is an incorrect indentation.
- TabError: Raised when there is an incorrect tab.
- SystemExit: Raised when the sys.exit() function is called.
- StopIteration: Raised when the next() method of an iterator does not point to any object.
- NotImplementedError: Raised when an abstract method that needs to be implemented in a subclass is not actually implemented.
- IndentationError: Raised when there is an incorrect indentation.
- TabError: Raised when there is an incorrect tab.
- SystemError: Raised when the interpreter detects an internal error.
- UnicodeError: Raised when a Unicode-related encoding or decoding error occurs.
- UnboundLocalError: Raised when a reference is made to a local variable in a function or method, but no value has been assigned to it.
- AssertionError: Raised when an assert statement fails.
- ArithmeticError: Raised when an error occurs in numeric calculations.
- FloatingPointError: Raised when a floating point operation fails.
3. How To Deal With Python Exception?
- To treat Python exceptions, you should use the try and except statements.
- The try statement allows you to test a block of code for errors.
- The except statement allows you to handle the error.
- You can also use the finally statement to execute code, regardless of the result of the try– and except statements.
- 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)
- 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")
- 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)
- 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)
- 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)
- 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)
- In Python, the assert statement is used to check if a condition is true, and if not, raise an AssertionError exception.
- It is used for debugging purposes to make sure that the code is behaving as expected.
- 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