<span id="7ztzv"></span>
<sub id="7ztzv"></sub>

<span id="7ztzv"></span><form id="7ztzv"></form>

<span id="7ztzv"></span>

        <address id="7ztzv"></address>

            Previous Page

            Up One Level

            Next Page

            Python ???

            Contents

            ????? 7. ???????? ????? Python ??? ??? 9. ??


            ????



             
            8.
            ???????

            ???????????????????????????????????????????????????????????????????????Python??????????????????????????? syntax errors and exceptions????

             
            8.1
            ??????

            ???????????????????????????Python?????????????????

            >>> while True print 'Hello world'
              File "<stdin>", line 1, in ?
                while True print 'Hello world'
                               ^
            SyntaxError: invalid syntax

            ??????????????????????????????????????????????????????????????????????????????????????????????????print???????????????????e???:???????????????????????????????????????????????????????

             
            8.2
            ??

            ????????????????????????????????????????????????????????????????????????????????????????????????????????????Python???????????????????????????????????????????????????

            >>> 10 * (1/0)
            Traceback (most recent call last):
              File "<stdin>", line 1, in ?
            ZeroDivisionError: integer division or modulo by zero
            >>> 4 + spam*3
            Traceback (most recent call last):
              File "<stdin>", line 1, in ?
            NameError: name 'spam' is not defined
            >>> '2' + 2
            Traceback (most recent call last):
              File "<stdin>", line 1, in ?
            TypeError: cannot concatenate 'str' and 'int' objects

            ????????????????????????????????????????????????????????????????????????????????????????????? ZeroDivisionError ???????????? NameError??????????? TypeError ???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

            ??????????????????????????????????????????????????????????

            ?????????????????????????????????????????????????????????????????????????????????????

            Python ?????? ???????????????????^

             
            8.3
            ??????

            ??????????????????????????????????????????????????????????????????????????????????????????????????????? Control-C ????????????????????????????????????????????????????? KeyboardInterrupt ????

            >>> while True:
            ...     try:
            ...         x = int(raw_input("Please enter a number: "))
            ...         break
            ...     except ValueError:
            ...         print "Oops! That was no valid number.  Try again..."
            ...

            try ??????????????

            ???try ???????????? except ????????????????????????????????????????? ??????????????????try???????????????????try????????????????????????????????except???????????????????????????????

            ... except (RuntimeError, TypeError, NameError):
            ...     pass

            ??????except??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

            import string, sys
            
            try:
                f = open('myfile.txt')
                s = f.readline()
                i = int(string.strip(s))
            except IOError, (errno, strerror):
                print "I/O error(%s): %s" % (errno, strerror)
            except ValueError:
                print "Could not convert data to an integer."
            except:
                print "Unexpected error:", sys.exc_info()[0]
                raise

            try ... except ???????????? else ????? ?????????????????except????????try?????????????????????????????????????????

            for arg in sys.argv[1:]:
                try:
                    f = open(arg, 'r')
                except IOError:
                    print 'cannot open', arg
                else:
                    print arg, 'has', len(f.readlines()), 'lines'
                    f.close()

            ??? else ?????? try ???????????????????????????? try ... except ???????????????????????????????????????

            ???????????????????????????????????????????????????????????????????????????????

            ???????????????????? except ????????????????????????????????????????? instance.args ????????????????????????????? __getitem__ ?? __str__ ??????????????????????????????????? .args??

            >>> try:
            ...    raise Exception('spam', 'eggs')
            ... except Exception, inst:
            ...    print type(inst)     # the exception instance
            ...    print inst.args      # arguments stored in .args
            ...    print inst           # __str__ allows args to printed directly
            ...    x, y = inst          # __getitem__ allows args to be unpacked directly
            ...    print 'x =', x
            ...    print 'y =', y
            ...
            <type 'instance'>
            ('spam', 'eggs')
            ('spam', 'eggs')
            x = spam
            y = eggs

            ?????????????????????????????????????????????????????????“???”???????????

            ??????????????????????????try??????????????????????????????????????????????????????????????

            >>> def this_fails():
            ...     x = 1/0
            ... 
            >>> try:
            ...     this_fails()
            ... except ZeroDivisionError, detail:
            ...     print 'Handling run-time error:', detail
            ... 
            Handling run-time error: integer division or modulo

             
            8.4
            ?????

            ???????????????????????????? raise ????????????????

            >>> raise NameError, 'HiThere'
            Traceback (most recent call last):
              File "<stdin>", line 1, in ?
            NameError: HiThere

            ???????????????????????????????????????????????

            ????????????????????????????raise ???????????????????????????

            >>> try:
            ...     raise NameError, 'HiThere'
            ... except NameError:
            ...     print 'An exception flew by!'
            ...     raise
            ...
            An exception flew by!
            Traceback (most recent call last):
              File "<stdin>", line 2, in ?
            NameError: HiThere

             
            8.5
            ??????????

            ????????????????????????????????????????????????????????? Exception ???????????

            >>> class MyError(Exception):
            ...     def __init__(self, value):
            ...         self.value = value
            ...     def __str__(self):
            ...         return repr(self.value)
            ... 
            >>> try:
            ...     raise MyError(2*2)
            ... except MyError, e:
            ...     print 'My exception occurred, value:', e.value
            ... 
            My exception occurred, value: 4
            >>> raise MyError, 'oops!'
            Traceback (most recent call last):
              File "<stdin>", line 1, in ?
            __main__.MyError: 'oops!'

            ????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????E?????????????????????????????????????????????

            class Error(Exception):
                """Base class for exceptions in this module."""
                pass
            
            class InputError(Error):
                """Exception raised for errors in the input.
            
                Attributes:
                    expression -- input expression in which the error occurred
                    message -- explanation of the error
                """
            
                def __init__(self, expression, message):
                    self.expression = expression
                    self.message = message
            
            class TransitionError(Error):
                """Raised when an operation attempts a state transition that's not
                allowed.
            
                Attributes:
                    previous -- state at beginning of transition
                    next -- attempted new state
                    message -- explanation of why the specific transition is not allowed
                """
            
                def __init__(self, previous, next, message):
                    self.previous = previous
                    self.next = next
                    self.message = message

            ????????????????????????????“Error????

            ??????????????????????????????????????????????????????????????????????????????? 9??“??”??

             
            8.6
            ???????????

            try ???????????????????????????????????????????????????

            >>> try:
            ...     raise KeyboardInterrupt
            ... finally:
            ...     print 'Goodbye, world!'
            ... 
            Goodbye, world!
            Traceback (most recent call last):
              File "<stdin>", line 2, in ?
            KeyboardInterrupt

            ????try???????????????? finally ??????????????????????????finally?????????????????????? try ??B?? break ?? return ????????????finally ???

            ??finally ????????????????????????????????????????????????????????????????

            ?? try ?????????????? except ??????? finally ??????????????n


            Previous Page

            Up One Level

            Next Page

            Python ???

            Contents

            ????? 7. ???????? ????? Python ??? ??? 9. ??


            Release 2.3, documentation updated on July 29, 2003.

            See About this document... for information on suggesting changes.
            ?????, @ssv
            <span id="7ztzv"></span>
            <sub id="7ztzv"></sub>

            <span id="7ztzv"></span><form id="7ztzv"></form>

            <span id="7ztzv"></span>

                  <address id="7ztzv"></address>

                      ŷ