“This is the 10th day of my participation in the August Gwen Challenge.

An exception is an error detected at runtime. Computer languages define exception types for possible errors. When an error raises the corresponding exception, the exception handler will be started to restore the normal operation of the program.

1. Summary of Python standard exceptions

  • BaseException: The base class for all exceptions
  • Exception: Base class for regular exceptions
  • StandardError: Base class for all built-in standard exceptions
  • ArithmeticError: The base class for all numeric calculation exceptions
  • FloatingPointError: Floating-point calculation exception
  • OverflowError: The number of operations exceeds the upper limit
  • ZeroDivisionError: The divisor is zero
  • AssertionError: The assert statement failed
  • AttributeError: Attempts to access unknown object attributes
  • EOFError: No built-in input, EOF flag is reached
  • EnvironmentError: Base class for operating system exceptions
  • IOError: the input/output operation failed
  • OSError: an exception raised by the operating system (such as opening a file that does not exist)
  • WindowsError: System call failure
  • ImportError: When importing a module fails
  • KeyboardInterrupt: The user interrupts execution
  • LookupError: Base class for invalid data queries
  • IndexError: The index is out of the range of the sequence
  • KeyError: Searches for a non-existent keyword in the dictionary
  • MemoryError: Memory overflow (memory can be freed by deleting objects)
  • NameError: Attempts to access a variable that does not exist
  • UnboundLocalError: Access an uninitialized local variable
  • ReferenceError: Weak references attempt to access objects that have already been garbage collected
  • RuntimeError: General runtime exception
  • NotImplementedError: method not yet implemented
  • SyntaxError: an exception caused by a SyntaxError
  • IndentationError: Exception caused by indentation errors
  • TabError: a combination of Tab and space
  • SystemError: General interpreter system exception
  • TypeError: Invalid operations between different types
  • ValueError: Invalid argument passed
  • UnicodeError: Unicode-related exception
  • UnicodeDecodeError: Exception during Unicode decoding
  • UnicodeEncodeError: Exception caused by A Unicode encoding error
  • UnicodeTranslateError: Exception caused by a Unicode conversion error

There are hierarchical relationships within the exception system. Some of the relationships in Python’s exception system are as follows:


2. Summary of Python standard warnings

  • Warning: The base class for warnings
  • DeprecationWarning: A warning about deprecated features
  • FutureWarning: A warning that the semantics of a construct will change in the future
  • UserWarning: Warning generated by user code
  • PendingDeprecationWarning: warning about properties will be discarded
  • RuntimeWarning: Indicates a warning about suspicious runtime behavior
  • SyntaxWarning: Warning of suspicious syntax
  • ImportWarning: Warning to be triggered during module import
  • UnicodeWarning: Unicode-related warning
  • BytesWarning: Warning related to bytes or bytecodes
  • ResourceWarning: A warning related to resource usage

3. Try-except statement

  • concept

    • The try statement works like this:

      • First, executiontryClause (in keywordtryAnd keywordexceptBetween statements)
      • If no exception occurs, ignore itexceptClause,tryThe clause terminates after execution.
      • If you’re executingtryException occurs in the process of the clause, thentryThe rest of the clause is ignored. If the type of exception andexceptThe following names match, then the correspondingexceptThe clause will be executed. The last executiontryThe code after the statement.
      • If an exception is not associated with anyexceptMatch, then the exception will be passed to the upper leveltryIn the.
  • code

Try: f = open('test.txt') print(f.read()) f.close() except OSError: Error # A try statement may contain more than one except clause to handle different specific exceptions. At most, only one branch will be executed. try: int("abc") s = 1 + '1' f = open('test.txt') print(f.read()) f.close() except OSError as error: Print (' open file error \n cause: '+ STR (error)) except TypeError as error: Print (' type error \n cause: '+ STR (error)) except ValueError as error: Print (' value error \n cause: '+ STR (error)) # tuple catch exception # An except clause can handle multiple exceptions at the same time, and these exceptions will be grouped in parentheses as a tuple. try: s = 1 + '1' int("abc") f = open('test.txt') print(f.read()) f.close() except (OSError, TypeError, ValueError) as error: Print (' Error! \n Cause: '+ STR (error))Copy the code

4. Try-exception-finally statement

  • concept

    • No mattertryIs there an exception in the clause,finallyClauses are executed.
    • If an exception is intryClause is thrown without anyexceptIntercept it, and the exception will be infinallyThe clause is thrown after execution.
  • code

    Try: print('1'+2) f = open('test.txt') print(f.read()) f.close() except OSError: Print (' error opening file ') finally: print(' I must execute ')Copy the code

5. Try-exception-else statements

  • concept

    • If thetryThe clause executes without exception, and Python will executeelseThe statement after the statement.
  • code

    Else try: print(1) except OSError: print(' error in opening file ') else: print(' error in opening file ') F = open('test.txt') print(f.read()) f.close() except OSError: print(' error ') else: Print (' It's nice to have no errors ') # If you use else and finally,else should come before finally, otherwise, try: F = open('test.txt') print(f.read()) f.close() except OSError: print(' error ') else: print(' error ') finally: Print (' I have to do it ')Copy the code

5. Raise the statement

  • concept

    • Python USESraiseStatement throws a specified exception.
  • code

    Try: raise NameError(except NameError as error: print(error)Copy the code

exercises:

1. Guess the numbers

Title description:

The computer produces a random number between zero and 100, and then asks the user to guess. If the user guesses a number larger than the number, the prompt is too large, otherwise the prompt is too small, and when the user just guesses correctly, the computer will prompt, “Congratulations, you guessed the number is…….” . The program outputs the number of guesses the user has made before each guess. If the user enters a number that is not at all, the program tells the user that “input is invalid.”

(Try to use the try catch exception handling structure to handle the input case)

Random module is used to obtain random numbers.

Code:

import random num = 0; RandomNum = random.randint(0,100) while 1: num+=1; Print (" num ",num," guess ") try: inputStr = input(" input "); Print (inputStr,type(inputStr)) if(int(inputStr) > randomNum): print(int(inputStr) < randomNum) Print (" TypeError,ValueError ") else: print(" TypeError ") break except (TypeError,ValueError): print(" TypeError ")Copy the code

\