As in all High level languages,
Python also provides ways for handling Issues.
Python provides 2 features to handle any unexpected error in the Python
programs.
Exception Handling
Assertions
Exception Handling – An
Exception is an event that occurs during an execution of program that disrupts
the flow of the program. Normally when a Python program encounters with a
situation that it cannot handle, it raises and exception.
These generated exceptions
needs to be handled correctly or the program will terminate.
Try – Except – Python programs
are written inside a try-except block so that if there is any code that might
cause a issues, it will be handled. The program is written inside a try block. After the try: block, include
an except: statement, followed by a block of code which
handles the problem as elegantly as possible.
Here is the Exception Handling
syntax,
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this
block.
except ExceptionII:
If there is ExceptionII, then execute this
block.
......................
else:
If there is no exception then execute this
block.
Some important points to
remember are,
1) a single try statement can
have multiple except Statements so that
when a try block contains statements that may throw a different type of
exceptions.
2) We can have our own generic
except clause, which can handle exceptions.
3) The else clause in the
except statement above is executed only when there are no exceptions raised
AN Example for exception
handling would look like this,
>>> try:
... fh =
open("Master.txt","w")
... print fh.name
... except IOError:
... print "Error Cannot Find File"
... else:
... print "File Obtained"
...
Master.txt
File Obtained
Except Statement with no
Exceptions – In the above snippet, if we observe we have an IOError defined in
the except clause. We can also write except clause with no exceptions defined.
This is considered a bad programming practice though it catches all the
exceptions but will not let the programmer know what exactly the Exceptions is.
You can also use the same except statement
to handle multiple exceptions like,
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.
Finally Clause - An exception
allows one to handle any exceptions raised but there will be some cases where
though an exception raised, a piece of code needs to be executed. Such sort of
code is written in Finally. Consider when file is opened in read mode and tried
to write to it , then an exception is thrown and handled but at-last the opened
file needs to be closed. In this cases we write the closing of file in the
finally block. An syntax would look like this,
try:
Operations Here
Due to any exception, this may be skipped.
finally:
This would always be executed.
Exception Arguments – An
Exception in Python can have an argument which gives additional information
about the problem or the exception caught. The syntax will be like,
>>> def
ret_value(var):
... try:
... return int(var)
... except ValueError,Argument:
... print "Argument
Passed",Argument
...
>>>
ret_value("hello WOrld")
Argument Passed invalid literal
for int(): hello World
The variable receives the value
of the exception mostly containing the cause of the exception. The variable can
receive a single value or multiple values in the form of a tuple. This tuple
usually contains the error string, the error number, and an error location.
Raising an Exception – An
Exception can be raised when certain Exceptions are caught. Consider we have
our own custom exceptions raised when specific conditions met. Python allows us
to raise exceptions like,
raise [Exception [, args [,
traceback]]]
An Example of Raising an
Exception will be,
>>> def fun_name(var):
... if(var < 1):
... raise "Invalid Var",var
...
>>> fun_name(0)
Traceback (most recent call
last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in
fun_name
Invalid Var: 0
May I simply say what a relief to discover someone who truly understands what
ReplyDeletethey are talking about online. You certainly know how to bring an issue to light and make it important.
More people ought to look at this and understand this side of your
story. I was surprised you're not more popular because you certainly possess the gift.
Also visit my homepage :: grand theft auto san andreas online
Havee yoou ever considered creating an e-book or guest authoring
ReplyDeleteoon other sites? I have a blog centered on the same ideas you discuss and would love to have you sharre some
stories/information. I know my audience would appreciate yyour work.
If you are even remotely interested, feel free to ssnd me an e mail.
my webage sleep apnea curezone
Hi, i think that i saw you visited my blog thus i came to “return the favor”.I'm trying to find things to
ReplyDeleteimprove my web site!I suppose its ok to use some of your ideas!!
Here is my weblog: lasertest