A to Z of Python exception handling | Python try catch with example

  1. What is the exception in python?
  2. How can we handle run time exceptions in python?
  3. What is the syntax of the basic try-except block?
    1.  Basic syntax.
    2. Example: program to handle exceptions while opening a file.
  4. Which is the base exception class in python?
  5. How can we explicitly generate exceptions from python code?
  6. How many types of exceptions are in python?
  7. Python exception hierarchy.
  8. Python User-defined Exceptions.
      1. Example: The user-defined exception class, raised when the input string is empty.

1. What is the exception in python?

In python, the code statement may be syntactically correct but it gives error at run-time or execution time, so the errors detected at the execution time is known at Exception.

Jump to the top of the page↵

2. How can we handle run time exceptions in python?

It is possible to handle exceptions in python at execution time, to handle it we use try-except block. we can see the example of how to use the try-except here.

Jump to the top of the page↵

3. What is the syntax of the basic try-except block?

Below are the syntax of python try-except

3.1 Basic syntax:

try:
   statement1;
   statement2;
except Exception1:
   For Exception1, execute this block.
except Exception2:
   For Exception2, execute this block.
else:
   For No Exception, execute this block.

3.2 Example: Below is the program to handle exceptions while opening a file.

import sys
try:
    obj_file = open('sample_exception_handling.txt')
    str1 = obj_file.readline()
    int1 = int(str1.strip())
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("failed: string to integer conversion ")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise

Jump to the top of the page↵

4. Which is the base exception class in python?

In Python, the ‘BaseException‘ is the base exception class. All exceptions must be instances of a class that derives from BaseException.

Jump to the top of the page↵

5. How can we explicitly generate exceptions from python code?

By using the ‘raise’ statement you can generate exceptions from python code.

def raiseIO_Exception():
    raise IOError

Jump to the top of the page↵

6. How many types of exceptions are in python?

The BaseException class are mainly divided into 4 types of exceptions

  1. SystemExit
  2. KeyboardInterrupt
  3. GeneratorExit
  4. Exception

Jump to the top of the page↵

7. Python Exception Hierarchy

BaseException

  • SystemExit
  • KeyboardInterrupt
  • GeneratorExit
  • Exception
    1. StopIteration
    2. StopAsyncIteration
    3. ArithmeticError
      • FloatingPointError
      • OverflowError
      • ZeroDivisionError
    4. AssertionError
    5. AttributeError
    6. BufferError
    7. EOFError
    8. ImportError
    9. MemoryError
    10. NameError
    11. OSError
    12. ReferenceError
    13. RuntimeError
    14. SyntaxError
    15. SystemError
    16. TypeError
    17. ValueError
    18. Warning
      • DeprecationWarning
      • PendingDeprecationWarning
      • RuntimeWarning
      • SyntaxWarning
      • UserWarning
      • FutureWarning
      • ImportWarning
      • UnicodeWarning
      • BytesWarning
      • ResourceWarning

Jump to the top of the page↵

8. Python User-defined Exceptions

You can create your own User-defined Exceptions by deriving from the Exception class, either directly or indirectly.

8. 1 Example: The user-defined exception class, raised when the input string is empty.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug  3 19:42:09 2021
website : http://mycloudplace.com
@author: mycloudplace
"""
class MyBase_Error(Exception):
    """This is base class for other exceptions"""
    pass

class Empty_String_Error(MyBase_Error):
    """Raised when the input string is empty"""
    pass

if __name__ == "__main__":
    input_string=""
    try:
        if(input_string == ""):
            raise Empty_String_Error
        else:
            print("String is not empty")
    except Empty_String_Error:
        print("Empty_String_Error Exception raised !")

OUTPUT:

Empty_String_Error Exception raised

You can find the details of exceptions from the official links

Below is our previous articles on python

5 thoughts on “A to Z of Python exception handling | Python try catch with example”

  1. Pingback: Python reporting libraries | Python reporting tools to generate interactive and beautiful reports - Mycloudplace

  2. I must thank you for the efforts youve put in writing this site. I really hope to check out the same high-grade content from you in the future as well. In fact, your creative writing abilities has inspired me to get my very own site now 😉

Leave a Comment

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