Like Java, Pyton an exception object to represent an exception condition. When an error is encountered, an exception is thrown, and if the exception object is not processed or snapped, the program terminates execution with the so-called backtracking (Traceback);
>>> 1/0
Traceback (most recent):
File "<stdin>", line 1, in <module>
zerodivisionerror: Division by zero
Programs can manually throw exceptions by raise Exceptin
>>> Raise Exception
Traceback (most recent):
File "<stdin>", line 1, in <module>
Exception
>>> raise Exception ("Hello Exception")
Traceback (most recent):
File "<stdin>", line 1, in <module>
Exception:hello Exception
To customize the exception type, simply inherit the exception (or its subclasses);
>>> raise 1
Traceback (most recent):
File "<stdin>", line 1, in <module>
TypeError: Exceptions must derive from Baseexception
Unlike C + +, only exception classes can be thrown;
>>> class MyException (Exception):
... pass
...
>>> raise MyException
Traceback (most recent):
File "<stdin>", line 1, in <module>
__main__. MyException
Catching exceptions
Try
....
Except ExceptionType1 as E:
....
Except ExceptionType2:
....
Raise
except (ExceptionType3, ExceptionType4):
....
Except
...
...
Else :
...
finally :
...
Raise with no parameters is used to re-throw exceptions;exception (ExceptionType3, ExceptionType4) is more convenient than Java single-parameter mode;
Except with no parameters catches all types of exceptions, but cannot get exception objects, you can use except Baseexception as E to resolve (or exceptin)
>>> Try:
... 1/0
... except baseexception as E:
... print (e)
...
Division by zero
else's block executes without throwing an exception; finally with Java;
>>> Try:
... 1/0
... except Zerodivisionerror as e:
... print (e)
...
Division by zero
>>> Try:
... 1/0
... finally:
... print (' finally ')
...
Finally
Traceback (most recent):
File "<stdin>", line 2, in <module>
Zerodivisionerror:division by Zero
>>> def f ():
... try:
... return 1/0
... finally:
... return 2
...
>>> F ()
2
Python, Exception exception