Try : statement ... except Name of exception: statement ...
If no exception occurs, run the statement under try and, if an exception occurs, run the statement below except., the exception type after epcept only takes effect when the corresponding exception occurs.
a=10b=0try: = b / aprint(c)except IOError, Zerodivisionerror: passelse: Print ("no error")print(" Done ")
Try .... except...else statement, when no exception occurs, the statement in else is executed.
Inputvalue=input ("Pleaseinput a int data:")if type (inputvalue)!=type ( 1): raise valueerrorElse: print(inputvalue)
Raise throws an exception
If the input data is not an integer, a valueerror is raised
a=10b=0try: Print(A/b)finally: Print ("alwaysexcute")
Try ... finally
The statements in finally are executed, regardless of whether the exception occurred or not, until the end of the program.
a=10b=0try: Print(A/b)except: Print ("error") finally : Print ("alwaysexcute")
The finally statement can also be used with the except statement.
Customize a MyException class, inheriting exception. classmyexception (Exception):def __init__(self,message): Exception.__init__(self) self.message=message if the number entered is less than 10, a MyException exception is thrown: a=input ("Please input a num:")ifA<10: Try: RaiseMyException ("My excepition is raised") exceptmyexception,e:Print(E.message)
Exceptions can also be customized
Summary of common exceptions
Exception Name Description baseexception the base class of all exceptions Systemexit interpreter request exits Keyboardinterrupt user interrupts execution ( is usually the input^C) Exception General error base class Stopiteration iterator no more values Generatorexit Generator (Generator) exception to notify Exit Systemexit Python Interpreter request Exit StandardError all built-in standard exception base class Arithmeticerror All numeric calculation errors base class FL Oatingpointerror floating-point calculation error Overflowerror numeric operation exceeds maximum limit zerodivisionerror except (or modulo) 0 (all data types) Assertionerror Assertion statement failed Attributeerror object does not have this property eoferror does not have built-in input, reaching the EOF tag EnvironmentError operation Base class for system error IOError input/output operation failed OSError operating system error Windowserror system call failed Importerror Import module/object failed Keyboardinterrupt user interrupt execution (usually input^b) Lookuperror Invalid data query in the base class Indexerror sequence does not have this index (index) Keyerror mapping does not have this key Memoryerror memory overflow error (not fatal for Python interpreter) Nam Eerror not declared/Initialize Object (no property) unboundlocalerror Access uninitialized local variable referenceerror weak reference (Weak reference) attempts to access objects that have been garbage collected runtimeerror general operations Line error Notimplementederror method not implemented SyntaxError Python syntax error indentationerror indentation error Taberror Tab and Space mix Systemerror General interpreter system error TypeError invalid operation ValueError passed in an invalid parameter Unicodeerror Unicode-related error unicodedecodeerror Unicode decoding Error Unicodeencodeerror Unicode encoding when error unicodetranslateerror Unicode conversion when error warning warning base class deprecationwarning about deprecated Warning of the characteristics of the futurewarning about constructing future semantics overflowwarning old warnings about automatic promotion to long, pendingdeprecationwarning a warning that attributes will be discarded Runtimewarning Suspicious runtime behavior (runtime behavior) warning syntaxwarning suspicious syntax warnings userwarning user code generated warnings
Use of try else statements in Python