Thread: raising an exception in python
-
12-03-2011, 04:55 AM #1
raising an exception in python
Hi Guys,
I am back with a doubt again:
I read that we can "raise" and exception in python if our program detects and error condition, e.g.
Now my question is - are we bound to use built-in exceptions only for the "exception type"?Code:def get_num():
number = int(raw_input('Enter number: ')) if number < 0:raise ValueError, ' %s is not a positive number' % numberreturn number
The answer seems 'yes' to me. Could someone throw light on this topic please?
-
01-16-2012, 02:22 AM #2Garage Member
- Join Date
- Dec 2010
- Posts
- 57
- Thanks
- 38
- Thanked 18 Times in 8 Posts
Old post, but the answer is no. You can throw any exception, Program has no way of knowing it.
An example,
It outputs:-Code:if 123 == 12: pass else: raise ValueError
Correct me, if I am wrongCode:Traceback (most recent call last): File "<pyshell#73>", line 4, in <module> raise ValueError ValueError
-
01-18-2012, 05:06 AM #3
Thanks for responding mayjune though it seems you did not get my question -
CodeOutputCode:if 123 == 12: pass else: raise mayjune
Code:root@bt:~/Desktop/Python# ./taste.py Traceback (most recent call last): File "./taste.py", line 6, in <module> raise mayjune NameError: name 'mayjune' is not defined
-
02-21-2012, 02:18 PM #4
Sorry for so much late reply... I had not seen this thread.
You need to create your own error class to raise custom errors
e.g.
Code:class mayjune(Exception): def __init__(self, value): self.parameter = value def __str__(self): return repr(self.parameter) if 123 == 12: pass else: raise mayjune("My Error")Orkut id: neo1981
Blog: infosec-neo.blogspot.com
Nothing is Impossible*
*Conditions Apply
-
The Following User Says Thank You to neo For This Useful Post:
abhaythehero (02-23-2012)



LinkBack URL
About LinkBacks



Reply With Quote

Research Resources for MS...
Today, 12:25 PM in Web Application Penetration Testing