How to create my own exception for brackets?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Armando Santiag
    New Member
    • Dec 2010
    • 3

    #1

    How to create my own exception for brackets?

    i want to create my own exception with code saying whether or not someone has entered a ) after a (, for example (jdduu) is ok, but hkbvbhb)hkhb(, is not, how would i start
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    First you would create an algorithm to determine if the user entered unbalanced parentheses. You don't really need a user-defined exception. Just raise an exception based on a certain condition. But if you want to:
    Code:
    class UnbalancedParenthesesError(Exception):
        pass
    
    class NoParenthesesError(Exception):
        pass
    
    def getinput(prompt="Enter input enclosed by parentheses"):
        s = raw_input(prompt)
        i = s.find("(")
        j = s.find(")")
        if i < 0 or j < 0:
            raise NoParenthesesError("You left off the parentheses")
        elif j < i:
            raise UnbalancedParenthesesError("Your parentheses are unbalanced")
        return s
    
    print getinput()

    Comment

    • Armando Santiag
      New Member
      • Dec 2010
      • 3

      #3
      this method works for single parentheses for example (hcvhkdb), but not for parentheses within parentheses (jcdbjkbdcjb(23 8))

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        My example was never intended to be a solution. It was intended to be an example of a user-defined exception.

        Comment

        • Armando Santiag
          New Member
          • Dec 2010
          • 3

          #5
          your solution helped alot wit another exception i was working on, but im going to continue to try the brackets, will post if i come up with something

          Comment

          Working...