Results 1 to 4 of 4

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

  1. #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.

    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
    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
    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
    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

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
  •