Errors and Exception Handling in Python

Errors and Exception Handling in Python with Examples

In this article, I am going to discuss Errors and Exception Handling in Python with Examples. Please read our previous article where we discussed Functions in Python with Examples.

Errors in Python

Errors are problems in a program that causes the program to stop running. Exceptions, on the other hand, are raised when some internal events occur that disrupt the normal flow of the program. Python has two types of errors:

  1. Syntax errors
  2. Logical errors (Exceptions)

A syntax error is thrown when the proper syntax of the language is not followed.

# initialize the amount variable
amount = 10000
 # check if amount is greater than 2000
   print("amount is greater than 2000")

Errors and Exception Handling in Python with Examples

Logical Errors in Python

When running, an error that occurs after passing the syntax test is referred to as an exception or logical type. When we divide any number by zero, for example, the ZeroDivisionError exception is raised, and when we import a module that does not exist, the ImportError exception is raised.

# initialize the amount variable
marks = 2500
 # perform division with 0
a = marks / 0

Logical Errors in Python

Indentation error i.e. when the indentation is not correct

Indentation error i.e. when the indentation is not correct

Handling Errors in Python

When an error or an exception is raised, we handle it using the Handling method.

Exception Handling with Try/Except/Finally in Python

The Try/Except/Finally method can be used to handle errors. We write unsafe code in the try block, fallback code in the except block, and finally code in the finally block.

# put unsafe operation in try block
    print("code start")
    # unsafe operation perform
    print(1 / 0)
 # if error occur the it goes in except block
    print("an error occurs")
 # final code in finally block

Exception Handling with Try/Except/Finally in Python

Multiple Exception Handling in Python

Given a piece of code that can throw any of several different exceptions, one must account for all possible exceptions without creating duplicate code or long, meandering code passages. If you can handle multiple exceptions in a single block of code, you can group them together in a tuple, as shown in the code below:

except (URLError, ValueError, SocketTimeout):
The Standard Exception Hierarchy in Python

Python includes a plethora of built-in exceptions. All of these exceptions are part of the exceptions module, which is always loaded prior to the execution of any program. The structure below identifies the standard exception hierarchy and immediately follows with a description of each exception type.

This structure, which resembles a tree, demonstrates that all exceptions are descended from a base class called Exception. When we highlight the ImportErrorexception, we can see that it is a subclass of the StandardErrorclass. Furthermore, the StandardError class is a subclass of the Exception class. The structure is depicted in the table below.

Standard Exception Hierarchy in Python

The exception class is the root class. This base class is subclassed by all exception classes. Every user exception class should be descended from this one as well.

  1. SystemExit – It is an exception because it isn’t an error message. It can, however, be used to exit a program. The important thing to note is that no traceback message is returned by this exception.
  2. StandardError– The base class for all errors is StandardError (except for SystemExit, of course).
  3. When an interrupt key, such as CTRL+C, is pressed, it raises this interrupt.
  4. ImportError— This error is thrown when Python is unable to locate a module to import.

The base class for errors that occur outside of the Python environment is EnvironmentError. It is a subclass of the IOError and OSError classes.

  1. IOError— This error is caused by I/O operation errors.
  2. OSError— This is caused by operating system errors, which are typically generated by the os module.
  3. EOFError – When an End-of-File (EOF) error occurs, an EOFError exception is raised.
  4. RuntimeError— A type of exception raised by errors that aren’t covered by any of the other exceptions.
  5. NameError— This error is thrown when the interpreter encounters a name that does not exist in either the local or global namespaces.
  6. UnboundLocalError— This is a new exception added in version 1.6. It is a subclass of the NameErrorexception, and it throws an error if a local variable is undefined.
  7. AttributeError— This type of error is caused by attribute reference and attribute assignment errors. This exception will have a more friendly error message starting with version 1.6, which is expected to break some code that assumes the message is exactly equivalent to the attribute name.
  8. SyntaxError— This exception is thrown when there is a syntax error.
  9. TypeError— This exception is thrown when you attempt to apply a function operation to an object of the wrong type.
  10. AssertionError— This type of exception is thrown when an assert statement evaluates to false.
  11. LookupError is the root class for indexing and key errors. It is a subclass of the IndexError and KeyError classes.
  12. IndexError— This error is triggered by “sequence out of range” errors.
  13. When a key is not found in a dictionary, a KeyError is raised.
  14. ArithmeticError is the base class for all arithmetic errors. It is subclassed by the classes OverflowError, ZeroDivisionError, and FloatingPointError.
  15. OverflowError— This exception is thrown when the result is so large that the operation overflows.
  16. ZeroDivisionError— This error is thrown when an operation attempting to divide a number by zero is performed.
dict = { 1:"First",2:"Second"}

Errors and Exception Handling in Python with Examples

list = [13,14,15,16]

Errors and Exception Handling in Python with Examples

The following example is able to catch both IndexError and Key Error exceptions.

Modules in Python

Python modules are files that contain Python definitions and statements. Functions, classes, and variables can all be defined by a module. Runnable code can also be included in a module. Grouping related code into modules makes it easier to understand and use the code. It also helps to organize the code logically.

Import Module in Python – Import statement

When the interpreter comes across an import statement, it imports the module if it is in the search path. A search path is a list of directories that the interpreter looks through when importing a module. To import the module, for example, place the following command at the top of the script.

It should be noted that this does not directly import the functions or classes, but rather the module. The dot(.) operator is used to access the functions contained within the module.

import numpy

The from statement in Python allows you to import specific attributes from a module without importing the entire module.

from math import sqrt, factorial

Modules in Python

The * symbol, when used with the from import statement, imports all of the names from a module into the current namespace.

from math import *

Modules in Python

Module Search Path in Python

When the interpreter executes the preceding import statement, it looks for the module in a directory list compiled from the following sources:

  1. If the interpreter is being run interactively, the directory from which the input script was run, or the current directory, is returned.
  2. If the PYTHONPATH environment variable is set, this is the list of directories it contains. (The format for PYTHONPATH varies depending on the operating system, but it should be similar to the PATH environment variable.)
  3. A list of directories that are configured at the time Python is installed.

The resulting search path is accessible in the Python variable sys.path, which is obtained from a module named sys:

import sys

Module Search Path in Python

So, in order to ensure that your module is discovered, you must do one of the following:

  • Place the module in the same directory as the input script, or in the current directory if interactive.
  • Before starting the interpreter, change the PYTHONPATH environment variable to include the directory where the module is located. Alternatively, place the module in one of the directories already listed in the PYTHONPATH variable.
  • Put the module in one of the installation-dependent directories, to which you may or may not have write access depending on the operating system.
Package Installation Ways in Python

A package contains all of the files required by a module. Modules are Python code libraries that can be incorporated into your project. It is very simple to download a package. Open the command-line interface and instruct PIP to download the desired package. Navigate to the location of Python’s script directory on your command line and type the following:

C:\Users\AppData\Local\Programs\Python\Python36-32\Scripts>pip install numpy

In the next article, I am going to discuss Python Plotly for Data Science with Examples. Here, in this article, I try to explain Errors and Exception Handling in Python with Examples. I hope you enjoy this Errors and Exception Handling in Python article.

Leave a Reply

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