+ Reply to Thread
Results 1 to 4 of 4

Thread: raising an exception in python Share/Save - My123World.Com!

  1. #1
    Garage Newcomer RingZzer0 is on a distinguished road RingZzer0's Avatar
    Join Date
    Oct 2011
    Posts
    10
    Thanks
    3
    Thanked 1 Time in 1 Post

    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.

    Code:
    def get_num():
    number = int(raw_input('Enter number: ')) if number < 0:
    raise ValueError, ' %s is not a positive number' % number
    return number
    Now my question is - are we bound to use built-in exceptions only for the "exception type"?
    The answer seems 'yes' to me. Could someone throw light on this topic please?

  2. #2
    Garage Member mayjune is on a distinguished road
    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,

    Code:
    if 123 == 12:
        pass
    else:
        raise ValueError
    It outputs:-

    Code:
    Traceback (most recent call last):
      File "<pyshell#73>", line 4, in <module>
        raise ValueError
    ValueError
    Correct me, if I am wrong

  3. #3
    Garage Newcomer RingZzer0 is on a distinguished road RingZzer0's Avatar
    Join Date
    Oct 2011
    Posts
    10
    Thanks
    3
    Thanked 1 Time in 1 Post
    Thanks for responding mayjune though it seems you did not get my question -

    Code
    Code:
    if 123 == 12:
        pass
    else:
        raise mayjune
    Output
    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

  4. #4
    neo
    neo is offline
    InfoSec Consultant neo is on a distinguished road
    Join Date
    Jul 2010
    Posts
    282
    Thanks
    94
    Thanked 52 Times in 35 Posts
    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

  5. The Following User Says Thank You to neo For This Useful Post:

    abhaythehero (02-23-2012)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts