Python Exception Handling

exception handling in python

Python Exception Handling : Python provides two very important features to handle any unexpected error in your Python programs and to add debugging capabilities in them −

  • Exception Handling 
  • Assertions 

List of Python Exception Handling −

Sr.No.Exception Name & Description
1Exception : Base class for all exceptions
2StopIteration : Raised when the next() method of an iterator does not point to any object.
3SystemExit : Raised by the sys.exit() function.
4StandardError : Base class for all built-in exceptions except StopIteration and SystemExit.
5ArithmeticError : Base class for all errors that occur for numeric calculation.
6OverflowError : Raised when a calculation exceeds maximum limit for a numeric type.
7FloatingPointError : Raised when a floating point calculation fails.
8ZeroDivisionError : Raised when division or modulo by zero takes place for all numeric types.
9AssertionError : Raised in case of failure of the Assert statement.
10AttributeError : Raised in case of failure of attribute reference or assignment.
11EOFError : Raised when there is no input from either the raw_input() or input() function and the end of file is reached.
12ImportError : Raised when an import statement fails.
13KeyboardInterrupt : Raised when the user interrupts program execution, usually by pressing Ctrl+c.
14LookupError : Base class for all lookup errors.
15IndexError : Raised when an index is not found in a sequence.
16KeyError : Raised when the specified key is not found in the dictionary.
17NameError : Raised when an identifier is not found in the local or global namespace.
18UnboundLocalError : Raised when trying to access a local variable in a function or method but no value has been assigned to it.
19EnvironmentError : Base class for all exceptions that occur outside the Python environment.
20IOError : Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist.
21IOError : Raised for operating system-related errors.
22SyntaxError : Raised when there is an error in Python syntax.
23IndentationError : Raised when indentation is not specified properly.
24SystemError : Raised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit.
25SystemExit : Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit.
26TypeError : Raised when an operation or function is attempted that is invalid for the specified data type.
27ValueError : Raised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified.
28RuntimeError : Raised when a generated error does not fall into any category.
29NotImplementedError : Raised when an abstract method that needs to be implemented in an inherited class is not actually implemented.

The problem without handling exceptions

As we have already discussed, the exception is an abnormal condition that halts the execution of the program.

Suppose we have two variables a and b, which take the input from the user and perform the division of these values. What if the user entered the zero as the denominator? It will interrupt the program execution and through a ZeroDivision exception. Let’s see the following example.

Example:


a = int(input("Enter a:"))    
b = int(input("Enter b:"))    
c = a/b  
print("a/b = %d" %c)    
    
#other code:    
print("Hi I am other part of the program")  

Output:

Enter a:10
Enter b:0
Traceback (most recent call last):
  File "exception-test.py", line 3, in <module>
    c = a/b;
ZeroDivisionError: division by zero

Raising exceptions

An exception can be raised forcefully by using the raise clause in Python. It is useful in in that scenario where we need to raise an exception to stop the execution of the program.

For example, there is a program that requires 2GB memory for execution, and if the program tries to occupy 2GB of memory, then we can raise an exception to stop the execution of the program.

The syntax to use the raise statement is given below.

Syntax:

raise Exception_class,<value>    

Example:

try:    
    age = int(input("Enter the age:"))    
    if(age<18):    
        raise ValueError   
    else:    
        print("the age is valid")    
except ValueError:    
    print("The age is not valid")    

Output:

Enter the age:17
The age is not valid

Custom Exception

The Python allows us to create our exceptions that can be raised from the program and caught using the except clause. However, we suggest you read this section after visiting the Python object and classes.

Consider the following example.

Example:

class ErrorInCode(Exception):      
    def __init__(self, data):      
        self.data = data      
    def __str__(self):      
        return repr(self.data)      
      
try:      
    raise ErrorInCode(2000)      
except ErrorInCode as ae:      
    print("Received error:", ae.data)      

Output:

Received error: 2000

Recommended Posts:

Spread the love

Leave a Comment

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