#12 - Python Errors

#12 - Python Errors

By Ifeanyi Omeata


Topics:


1. Python Errors
2. Python Built-in Exceptions
3. Error Exception Handling - Try,Except,Else,Finally
4. Customised Errors - Raise
5. Stack Trace


1. Python Errors


>>Return to Menu
Python errors can be broadly classified into two classes:

  • Syntax errors
  • Logical errors (Exceptions)
  • Syntax errors are caused by not following the proper structure (syntax) of the language is called syntax error or parsing error.
  • For Example, when a colon : is missing in the if statement: image.png
  • Logical errors (Exceptions) occur at runtime.
  • For Example, when we try to open a file(for reading) that does not exist (FileNotFoundError), or try to divide a number by zero (ZeroDivisionError), or try to import a module that does not exist (ImportError). image.png
  • Whenever these types of runtime errors occur, Python creates an exception object that prints a traceback to that error along with some details about why that error occurred. image.png


2. Python Built-in Exceptions


>>Return to Menu
There are plenty of built-in exceptions in Python that are raised when corresponding errors occur. We can view all the built-in exceptions using the built-in local() function as follows:

print(dir(locals()['__builtins__']))

Some of the common built-in exceptions in Python programming along with the error that cause them are listed below:

  • AssertionError = Raised when an assert statement fails.
  • AttributeError = Raised when attribute assignment or reference fails.
  • EOFError = Raised when the input() function hits end-of-file condition.
  • FloatingPointError = Raised when a floating point operation fails.
  • GeneratorExit = Raised when a generator's close() method is called.
  • ImportError = Raised when the imported module is not found.
  • IndexError = Raised when the index of a sequence is out of range.
  • KeyError = Raised when a key is not found in a dictionary.
  • KeyboardInterrupt = Raised when the user hits the interrupt key (Ctrl+C or Delete).
  • MemoryError = Raised when an operation runs out of memory.
  • NameError = Raised when a variable is not found in local or global scope.
  • NotImplementedError = Raised by abstract methods.
  • OSError = Raised when system operation causes system related error.
  • OverflowError = Raised when the result of an arithmetic operation is too large to be represented.
  • ReferenceError = Raised when a weak reference proxy is used to access a garbage collected referent.
  • RuntimeError = Raised when an error does not fall under any other category.
  • StopIteration = Raised by next() function to indicate that there is no further item to be returned by iterator.
  • SyntaxError = Raised by parser when syntax error is encountered.
  • IndentationError = Raised when there is incorrect indentation.
  • TabError = Raised when indentation consists of inconsistent tabs and spaces.
  • SystemError = Raised when interpreter detects internal error.
  • SystemExit = Raised by sys.exit() function.
  • TypeError = Raised when a function or operation is applied to an object of incorrect type.
  • UnboundLocalError = Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable.
  • UnicodeError = Raised when a Unicode-related encoding or decoding error occurs.
  • UnicodeEncodeError = Raised when a Unicode-related error occurs during encoding.
  • UnicodeDecodeError = Raised when a Unicode-related error occurs during decoding.
  • UnicodeTranslateError = Raised when a Unicode-related error occurs during translating.
  • ValueError = Raised when a function gets an argument of correct type but improper value.
  • ZeroDivisionError = Raised when the second operand of division or modulo operation is zero.


3. Error Exception Handling - Try,Except,Else,Finally


>>Return to Menu

try:
    # code that may cause an exception
except:
    # code to run when exception occurs

Sample:

try:
    numerator = 10
    denominator = 0

    result = numerator / denominator
    print(result)

    my_list = [1,2,3]
    print(my_list[10])

except ZeroDivisionError as e:
    print(f"Denominator cannot be 0. Please try again. Err: {e}.")
except IndexError as e:
    print(f"Index cannot be greater than size of list. Err: {e}.")    
else:
    print("Program was successful!")    
finally:
    print("Program ends")

image.png Other Examples: image.png image.png image.png image.png


4. Customised Errors - Raise


>>Return to Menu

def run_time_err():
    raise RuntimeError("This will not work!")

def index_err():
    raise IndexError("You have exceeded the List limit.")

my_list = [2,3,4]

if len(my_list) < 5:    
    run_time_err()

image.png Other Examples: image.png image.png


5. Stack Trace


>>Return to Menu
Python prints a stack trace when your code throws an exception. A stack trace is often also referred to as a stack traceback, backtrace, or traceback. The Python stack trace holds a lot of valuable information that helps you identify the source of the problem. Understanding what information a Python stack trace provides is vital to becoming a better Python programmer.
A stack trace prints all the calls prior to the function that raised an exception. In all cases, the last line of a stack trace prints the most valuable information as here the error gets printed. All information above the thrown error consists of function calls that help you to trace the issue faster.
For Example: image.png image.png The Most Common Python Stack Traces are:

  • AttributeError
    Your code will throw an AttributeError when you try to access an attribute on an object that doesn’t have this attribute defined. image.png image.png
  • ImportError
    Your Python script will throw an ImportError when you mess up the import statement. It is raised when the import statement has troubles trying to load a module. Also raised when the “from list” in from … import has a name that cannot be found. image.png image.png
  • SyntaxError
    The parser encounters an error in the Syntax. image.png image.png
  • TypeError
    Raised when an operation or function is applied to an object of inappropriate type.
  • ValueError
    Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.
  • KeyError
    Raised when a mapping (dictionary) key is not found in the set of existing keys.
  • IndexError
    Raised when a sequence subscript is out of range.
  • IOError
    Raised when an I/O operation fails for an I/O-related reason.
  • ZeroDivisionError
    This error is thrown when you try to divide a number by a zero value. image.png

#End


Hope you enjoyed this! :) Follow me for more contents...


Get in Touch:
ifeanyiomeata.com

Youtube: youtube.com/c/IfeanyiOmeata
Linkedin: linkedin.com/in/omeatai
Twitter: twitter.com/iomeata
Github: github.com/omeatai
Stackoverflow: stackoverflow.com/users/2689166/omeatai
Hashnode: hashnode.com/@omeatai
Medium: medium.com/@omeatai
© 2022