Exception Handling in Python
An exception is an error which happens at the time of execution of a program. However,
while running a program, Python generates an exception that should be handled to
avoid your program to crash. In Python language, exceptions trigger automatically on
errors, or they can be triggered and intercepted by your code.
The exception indicates that, although the event can occur, this type of event happens
infrequently. When the method is not able to handle the exception, it is thrown to its
caller function. Eventually, when an exception is thrown out of the main function, the
program is terminated abruptly.
Common Examples of Exception:
Division by Zero
Accessing a file which does not exist.
Addition of two incompatible types
Trying to access a nonexistent index of a sequence
Removing the table from the disconnected database server.
ATM withdrawal of more than the available amount
Rules of Exceptions
Exceptions must be class objects
For class exceptions, you can use try statement with an except clause which
mentions a particular class.
Even if a statement or expression is syntactically correct, it may display an error
when an attempt is made to execute it.
Errors found during execution are called exceptions, and they are not
unconditionally fatal.
Python Exception Handling Mechanism
Exception handling is managed by the following 5 keywords:
try
catch
finally
throw
raise
Try Statement
A try statement includes keyword try, followed by a colon (:) and a suite of code
in which exceptions may occur. It has one or more clauses.
During the execution of the try statement, if no exceptions occurred then, the
interpreter ignores the exception handlers for that specific try statement.
In case, if any exception occurs in a try suite, the try suite expires and program
control transfers to the matching except handler following the try suite.
Syntax:
try:
statement(s)
The catch Statement
Catch blocks take one argument at a time, which is the type of exception that it is
likely to catch. These arguments may range from a specific type of exception which can
be varied to a catch-all category of exceptions.
Rules for catch block:
You can define a catch block by using the keyword catch
Catch Exception parameter is always enclosed in parentheses
It always represents the type of exception that catch block handles.
An exception handling code is written between two {} curly braces.
You can place multiple catch block within a single try block.
You can use a catch block only after the try block.
All the catch block should be ordered from subclass to superclass exception.
Example:
try
}
catch (ArrayIndexOutOfBoundsException e)
{
[Link]("Caught first " + [Link]());
}
catch (IOException e)
{
[Link]("Caught second " + [Link]());
}
Finally Statement in Python
Finally block always executes irrespective of an exception being thrown or not.
The final keyword allows you to create a block of code that follows a try-catch block.
Finally, clause is optional. It is intended to define clean-up actions which should
be that executed in all conditions.
try:
raise KeyboardInterrupt
finally:
print 'welcome, world!'
Output
Welcome, world!
KeyboardInterrupt
Finally, clause is executed before try statement.
Raise Statement in Python
The raise statement specifies an argument which initializes the exception object. Here,
a comma follows the exception name, and argument or tuple of the argument that
follows the comma.
Syntax:
raise [Exception [, args [, traceback]]]
In this syntax, the argument is optional, and at the time of execution, the exception
argument value is always none.
Error vs. Exceptions
Error Exceptions
All errors in Python are the Exceptions include both checked
unchecked type. and unchecked type.
Exceptions can be recover by
Errors occur at run time which
handling them with the help of try-
unknown to the compiler.
catch blocks.
Errors are mostly caused by the
The application itself causes
environment in which an
exceptions.
application is running.
Examples:
Examples:
Checked Exceptions, SQL
OutofMemoryError
exception, NullPointerException,etc.