Home PC Games Linux Windows Database Network Programming Server Mobile  
  Home \ Programming \ Python exception summary     - Docker Build a Java compiler environment (Linux)

- MySQL / MariaDB database master-slave replication (Database)

- RHEL5.x RHEL6.x replace CentOS yum source (Linux)

- Zabbix installation under Linux (Server)

- Cross server / client backup command: rsync use (Server)

- Java memory area and memory overflow exception (Programming)

- Linux kernel source code analysis (Linux)

- How SSHfs mount a remote file system on Linux (Linux)

- CoreOS quick installation to get started on a PC (Linux)

- CentOS 6.7 compile and install LAMP (Server)

- Java precision four operations (Programming)

- Oracle table space create large files (Database)

- IP Security Policy is to learn how to prevent Ping and closed ports (Linux)

- Virt Related Command Summary (Linux)

- Installation Elementary OS Freya to do some settings (Linux)

- Teach you to diagnose problems with strace (Linux)

- Python developer of time-saving method (Programming)

- Hard disk encryption to protect data security (Linux)

- Windows Desktop use VNC remote connect Linux (Linux)

- To restore the last time applications running when Ubuntu user log in again (Linux)

  Python exception summary
  Add Date : 2017-08-31      
  Exception handling in Python

Sentence structure exception handling

     # Run try block and tries to catch the exception
except :
     # If name1 abnormal findings, then execute the block.
except (name2, name3):
     # If any exception occurs within a tuple, then capture it
except as :
     # If name4 exception occurs, then enter the statement block, and the exception instance variable named
     # Exceptions Exception occurred above all other than those listed
# If no exception occurs, it executes the statement block
# whether or not an exception occurs, it will execute the block.

and finally else is optional, there may be zero or more except, however, if there is an else, then there must be at least one except.
No matter how you specify an exception, this will always be identified by instances of objects, and most of the time at any given moment of activation. Once an exception somewhere in the program is captured by an except clause, it dies, unless it is caused by another re-raise statement or error.
raise statement

raise statement is used to manually throw an exception with the following call in several formats:

raise # You can create the instance before the raise statement or created in the raise statement.
raise #Python implicitly creates an instance of the class
raise name (value) # thrown while providing additional information value
The last raise # re-generated exception thrown
raise exception from E
Throw ValueError with additional information: raise ValueError ( 'we can only accept positive values')
When using the time from the second expression specifies another exception class or an instance, it will be appended to the __cause__ property throws an exception. If the exception thrown is not caught, Python standard error of the abnormal and as part of the message printed out:
For example, the following code:

except Exception as E:
    raise TypeError ( 'bad input') from E
Implementation of the results are as follows:

Traceback (most recent call last):
  File "hh.py", line 2, in
ZeroDivisionError: division by zero

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "hh.py", line 4, in
    raise TypeError ( 'bad input') from E
TypeError: bad input
assert statement

assert is mainly used to make assertions, more generally used in unit testing, time to do introduction.

with ... as statements

with statement supports a richer object-based protocol can be defined as a block of code support to enter and leave the operation.
statements with the corresponding environmental management protocol requirements are as follows:

Environmental manager must have __enter__ and __exit__ methods.
__enter__ method during initialization run, if there are children in the ass, __ enter__ function's return value will be assigned to the variable as clause, otherwise discarded.
Nested code block code execution.
If with the code block throws an exception, __ exit __ (type, value, traceback) method is called (with the exception details). These are also the same value returned by the sys.exc_info. If this method returns false, the exception will be raised again. Otherwise, the exception will be terminated. Under normal circumstances, an exception should be re-initiated, so in order to pass to the outside with the statement.
If no exception is thrown with a block of code, __ exit__ method will still be called, its type, value and traceback parameters are passed to None.
Here is a simple custom context management class.

class Block:
    def __enter __ (self):
        print ( 'entering to the block')
        return self
    def prt (self, args):
        print ( 'this is the block we do% s'% args)

    def __exit __ (self, exc_type, exc_value, exc_tb):
        if exc_type is None:
            print ( 'exit normally without exception')
            print ( 'found exception:% s, and detailed info is% s'% (exc_type, exc_value))
        return False

with Block () as b:
    b.prt ( 'actual work!')
    raise ValueError ( 'wrong')
If you log out to raise the above statement, it will exit gracefully.
In the absence of written off the raise statement, the results are as follows:

entering to the block
this is the block we do actual work!
found exception: , and detailed info is wrong
Traceback (most recent call last):
  File "hh.py", line 18, in
    raise ValueError ( 'wrong')
ValueError: wrong
Exception handler

If an exception occurs, so by calling sys.exc_info () function can return it contains three elements of a tuple. The first element is the class throws an exception, and the second is an example of the actual initiation of the third element traceback object that represents the call stack when an exception occurs first. If all goes well, it will return three None.

Exception Python's module definition Builtins

| Exception Name | Description |
| BaseException | Root class for all exceptions |
| SystemExit | Request termination of Python interpreter |
| KeyboardInterrupt | User interrupted execution (usually by pressing Ctrl + C) |
| Exception | Root class for regular exceptions |
| StopIteration | Iteration has no further values |
| GeneratorExit | Exception sent to generator to tell it to quit |
| SystemExit | Request termination of Python interpreter |
| StandardError | Base class for all standard built-in exceptions |
| ArithmeticError | Base class for all numeric calculation errors |
| FloatingPointError | Error in floating point calculation |
| OverflowError | Calculation exceeded maximum limit for numerical type |
| ZeroDivisionError | Division (or modulus) by zero error (all numeric types) |
| AssertionError | Failure of assert statement |
| AttributeError | No such object attribute |
| EOFError | End-of-file marker reached without input from built-in |
| EnvironmentError | Base class for operating system environment errors |
| IOError | Failure of input / output operation |
| OSError | Operating system error |
| WindowsError | MS Windows system call failure |
| ImportError | Failure to import module or object |
| KeyboardInterrupt | User interrupted execution (usually by pressing Ctrl + C) |
| LookupError | Base class for invalid data lookup errors |
| IndexError | No such index in sequence |
| KeyError | No such key in mapping |
| MemoryError | Out-of-memory error (non-fatal to Python interpreter) |
| NameError | Undeclared / uninitialized object (non-attribute) |
| UnboundLocalError | Access of an uninitialized local variable |
| ReferenceError | Weak reference tried to access a garbage collected object |
| RuntimeError | Generic default error during execution |
| NotImplementedError | Unimplemented method |
| SyntaxError | Error in Python syntax |
| IndentationError | Improper indentation |
| TabErrorg | Improper mixture of TABs and spaces |
| SystemError | Generic interpreter system error |
| TypeError | Invalid operation for type |
| ValueError | Invalid argument given |
| UnicodeError | Unicode-related error |
| UnicodeDecodeError | Unicode error during decoding |
| UnicodeEncodeError | Unicode error during encoding |
| UnicodeTranslate Error | Unicode error during translation |
| Warning | Root class for all warnings |
| DeprecationWarning | Warning about deprecated features |
| FutureWarning | Warning about constructs that will change semantically in the future |
| OverflowWarning | Old warning for auto-long upgrade |
| PendingDeprecation Warning | Warning about features that will be deprecated in the future |
| RuntimeWarning | Warning about dubious runtime behavior |
| SyntaxWarning | Warning about dubious syntax |
| UserWarning | Warning generated by user code |
- Linux Hard Disk Partition and file system management (Linux)
- Ubuntu 14.04 Install WordPress on Nginx (Server)
- C ++ casts New Standard Comments (Programming)
- Android will save the picture to see the album and timely (Programming)
- LVS + Keepalived the DR mode (Server)
- Java application server WildFly (Server)
- Zabbix configure DataGuard monitoring (Database)
- Three strategies to teach you to release the device memory (Linux)
- Linux LVM space expansion Demo (Linux)
- Linux directory permissions to read and execute permissions difference (Linux)
- Java String type time compare the size (Programming)
- Linux dd command applies amplification SWAP partition (Linux)
- Setting Linux desktop environment, achieve HiDPI display support (Linux)
- The Objects in JavaScript (Programming)
- Linux file and directory management - ls, cp, mv (Linux)
- MySQL monitoring tool -Innotop (Database)
- Python decorators to learn and practice the actual usage scenarios (Programming)
- Package the Python script file into an executable file (Programming)
- Sysdig: system troubleshooting tool (Linux)
- 64 Ubuntu 15.04 Linux kernel upgrade to Linux 4.1.0 (Linux)
  CopyRight 2002-2020 newfreesoft.com, All Rights Reserved.