Exception Handling
Exception Handling
Exception Handling
• Exception occurs.
• Exception handling in python.
• Handling exceptions.
• Raising an Exceptions.
• User Defined Exceptions.
• In-built exceptions.
• An exception is an event, which occurs during
the execution of a program, that disrupts the
normal flow of the program's instructions.
Raising an is a value for the exception argument. The argument is optional; if not supplied,
the exception argument is None.
exceptions: The final argument, traceback, is also optional (and rarely used in practice), and, if
present, is the traceback object used for the exception
Example:
def functionName( level ):
if level < 1:
raise "Invalid level!", level
# The code below to this would not be executed
# if we raise the exception
• Python also allows you to create your own exceptions by deriving
classes from the standard built-in exceptions.
• Here is an example related to RuntimeError. Here a class is created
that is subclassed from RuntimeError. This is useful when you need to
display more specific information when an exception is caught.
User • In the try block, the user-defined exception is raised and caught in the
except block. The variable e is used to create an instance of the class
Defined Networkerror.
• class Networkerror(RuntimeError):
Exceptions: • def __init__(self, arg):
• self.args = arg
• So once you defined above class, you can raise your exception as
follows:
• try:
• raise Networkerror("Bad hostname")
• except Networkerror:
• print e.args
1.ZeroDivisionError – Raised when division or modulo by zero
takes place for all numeric types.
2.NameError – Raised when name of keywords, identifiers.. etc. are
wrong.
3.IndentationError – Raised when an indentation is not properly
given.
4.IOError – 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.
5.EOFError – Raised when there is no input from either the
raw_input() or input() function and the end of the file is reached.