Sep 2, 2010

Python error and exceptions

while True:
try:
x=int(raw_input(Please enter a number))
break
except ValueError
print Please enter an integer value

This will handle the error if the user inputs an non-integer value.
In a program first the try clause runs. The exception clause runs only if try clause mane an exception.
If an exception occurs two things can be happend. first thing the exception will mach the exception clause and will excecute the code belongs to that thing. The other thing is an exception is not matching our names in the exception clause.

Try except and else
"else" part is a optional.But;

for arg in sys.argv[1:]:
try:
f=open(arg,'r')
except IOError:
print 'Can not open the file',arg
else:
print agr,'has'len(f.lreadlines()), 'lines'
f.close()

In a case like this, it is very useful. If the try clause excecute normaly it will go to the else part and excecute that code. This will not create any exceptions

Finally clause
If an exception occures or not, this clause will excecute.
try:
code
except:
code
finally:
code

In python it supports to create your own exceptions also.

Python classes

This is the way to write a simple class;

class MyClass:
i=234
def f(self):
return 'Hello World'
Now MyClass.i and MyClass.f are valid attributes.

Create an instance of an class.
x=MyClass()
And now we can use it as;
x.f
x.i

No comments:

Post a Comment

Your comments are always welcome ...