- What is the exception in python?
- How can we handle run time exceptions in python?
- What is the syntax of the basic try-except block?
- Which is the base exception class in python?
- How can we explicitly generate exceptions from python code?
- How many types of exceptions are in python?
- Python exception hierarchy.
- Python User-defined Exceptions.
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.
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.
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
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.
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
6. How many types of exceptions are in python?
The BaseException class are mainly divided into 4 types of exceptions
- SystemExit
- KeyboardInterrupt
- GeneratorExit
- Exception
7. Python Exception Hierarchy
BaseException
- SystemExit
- KeyboardInterrupt
- GeneratorExit
- Exception
- StopIteration
- StopAsyncIteration
- ArithmeticError
- FloatingPointError
- OverflowError
- ZeroDivisionError
- AssertionError
- AttributeError
- BufferError
- EOFError
- ImportError
- MemoryError
- NameError
- OSError
- ReferenceError
- RuntimeError
- SyntaxError
- SystemError
- TypeError
- ValueError
- Warning
- DeprecationWarning
- PendingDeprecationWarning
- RuntimeWarning
- SyntaxWarning
- UserWarning
- FutureWarning
- ImportWarning
- UnicodeWarning
- BytesWarning
- ResourceWarning
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
- File Handling Python With Examples | Python Input-Output Awesome Tips
- Modules in python tactics that can boost your python programming skills
- Python array | numpy for python | How to create numpy or np array in python
- Python Lambda Function With Examples | How To Create A New Anonymous function
- Python Useful Built-in Functions With Examples | How to create a new function
- python iteration | while loop | for loop with examples
- Python Data Types With Examples
- Python – installation indentation variable comments
- Python Programming Introduction
Pingback: Python reporting libraries | Python reporting tools to generate interactive and beautiful reports - Mycloudplace
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 😉
Thank you.
Good explanation with example.
Thank you.