Python[十三]:Excption

 

Excption

The try statement works as follows.

  • First, the try clause (the statement(s) between the try and except keywords) is executed.
  • If no exception occurs, the except clause is skipped and execution of the try statement is finished.
  • If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.
  • If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.
  • >>>while True: try: x=int(input('Please enter an number')) break except ValueError: print('Oops!not an number....') Please enter an numbersdf Oops!not an number.... Please enter an numberfsd Oops!not an number.... >>> import sys >>> try: f=open('myfile.txt') s=f.readline() i=int(s.strip()) except IOError as err: print('I/O error:{0}'.format(err)) except ValueError: print("Cound'tconvert data to an integer.") except: print('Unexcpted error:',sys.exc_info()[0]) raise I/O error:[Errno 2] No such file or directory: 'myfile.txt' >>> try: raise Exception('spam','eggs') except Exception as inst: print(type(inst)) #the exception instance print(inst.args) print(inst) x,y=inst.args print('x=',x) print('y=',y) <class 'Exception'> ('spam', 'eggs') ('spam', 'eggs') x= spam y= eggs >>> def this_fail(): x=1/0 >>> try: this_fails() except ZeroDivisionError as err: print('Handling run-time error:',err) Traceback (most recent call last): File "<pyshell#31>", line 2, in <module> this_fails() NameError: name 'this_fails' is not defined >>> try: this_fail() except ZeroDivisionError as err: print('Handling run-time error:',err) Handling run-time error: int division or modulo by zero >>> raise NameError('HiThere') Traceback (most recent call last): File "<pyshell#34>", line 1, in <module> raise NameError('HiThere') NameError: HiThere >>> try: raise NameError('Hi There') except NameError: print('An exception flew by!') raise An exception flew by! Traceback (most recent call last): File "<pyshell#40>", line 2, in <module> raise NameError('Hi There') NameError: Hi There >>> class MyError(Exception): def __init__(self,value): self.value=value def __str__(self): retirn repr(self.value) SyntaxError: invalid syntax (<pyshell#45>, line 5) >>> class MyError(Exception): def __init__(self,value): self.value=value def __str__(self): return repr(self.value) >>> try: raise MyError(2*2) except MyError as e: print('My exception occured,value:',e.value) My exception occured,value: 4 >>> class Error(Exception): pass class InputError(Error): SyntaxError: invalid syntax (<pyshell#55>, line 3) >>> try: raise KeyboardInterrupt finally: print(''Goodbye,World!) SyntaxError: invalid syntax (<pyshell#59>, line 4) >>> try: raise KeyboardInterrupt finally: print('Goodbye,World!') Goodbye,World! Traceback (most recent call last): File "<pyshell#61>", line 2, in <module> raise KeyboardInterrupt KeyboardInterrupt >>> def divide(x,y): try: result=x/y except ZeroDivisionError: print('division by zero') else: print('result is:'result) SyntaxError: invalid syntax (<pyshell#68>, line 7) >>> def divide(x,y): try: result=x/y except ZeroDivisionError: print('division by zero') else: print('result is:',result) finally: print('seecuting finnaly clause') >>> divide(2,1) result is: 2.0 seecuting finnaly clause >>> divide(2,0) division by zero seecuting finnaly clause >>> divide('2','1') seecuting finnaly clause Traceback (most recent call last): File "<pyshell#75>", line 1, in <module> divide('2','1') File "<pyshell#72>", line 3, in divide result=x/y TypeError: unsupported operand type(s) for /: 'str' and 'str' >>> with open('myfile.txt') as f: for line in f: print(line) Traceback (most recent call last): File "<pyshell#79>", line 1, in <module> with open('myfile.txt') as f: File "C:/Python30/lib/io.py", line 278, in __new__ return open(*args, **kwargs) File "C:/Python30/lib/io.py", line 222, in open closefd) File "C:/Python30/lib/io.py", line 615, in __init__ _fileio._FileIO.__init__(self, name, mode, closefd) IOError: [Errno 2] No such file or directory: 'myfile.txt' >>> 

 

你可能感兴趣的:(Python[十三]:Excption)