Exception in python:
Exception in python:
The process or event which occurs while at a time of execution of a program that disrupts the normal flow of programs is called Exception. In Python exception is an object which represents error respectively.
Python exception needs to be handle otherwise it will get quits and terminates.
Python exception handling:
To handle the exception in python try & except statement is used basically. It is suggested to include except statement after the try block.
- Multiple except statements can be possible in a single try useful when try to contain statements.
- You can furthermore supply a generic except clause, which handles any exception respectively.
- You should include else clause after except clause if the no exception raised. The else block is the best practice of coding that doesn’t need to try block.
Example:
try:
You do your operations here;
......................
except Exception1:
If there is Exception1, then execute this block.
except ExceptionII:
If there is Exception2, then execute this block.
......................
else:
If there is no exception then execute this block.
Except for clause with many exceptions in Python:
Example:
#try with multiple except clause to handle exception accordingly
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
Try and finally clause in python
Example:
#try with finally block.
try:
You do your operations here;
---------------------------------------------------
Due to any exception, this may be skipped.
finally:
This would always be executed.
-----------------------------------------------
User-defined exception Python:
Python also allows you to generate your possess exceptions by deriving classes beginning the standard built-in exceptions respectively.
Here is an instance connected to RuntimeError and here, a class is formed that is subclassed from RuntimeError. This is accommodating when you require to put on show more detailed information when an exception is wedged.
In Python the try block, the user-defined exception is raised and fixed apart from the block.
Example:
#example to explain about the try and except block
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args
