Python exception handling example details

  • 2020-04-02 13:32:48
  • OfStack

I. what is abnormal?
An exception is an event that occurs during the execution of a program and affects the normal execution of the program.
Normally, an exception occurs when Python fails to handle the program properly.
An exception is a Python object that represents an error.
When an exception occurs in a Python script, we need to catch and handle it, or the program will terminate execution.
2. Exception handling
Exceptions can be caught using the try/except statement.
The try/except statement detects errors in the try statement block, allowing the except statement to capture exception information and handle it.
If you don't want to end your program when an exception occurs, just catch it in try.

Exception syntax:
Here is a simple try... Except... Else syntax:

try:
< statements >        # Run something else 
except < The name > : 
< statements >        # If the try Part of it 'name' abnormal 
except < The name > . < data >:
< statements >        # If it triggers 'name' Exception to get additional data 
else:
< statements >        # If no exceptions occur 

The way try works is that when a try statement is started, python marks it in the context of the current program so that it can come back here when an exception occurs, the try clause executes first, and what happens next depends on whether an exception occurs during execution.

If an exception occurs when a statement following the try executes, python jumps back to the try and executes the first except clause that matches the exception, the exception is handled, and the control flow goes through the entire try statement (unless a new exception is thrown when the exception is handled).
If an exception occurs in a statement after the try without a matching except clause, the exception is passed to the upper try or to the top of the program (this will end the program and print the default error message).
If no exception occurs during the execution of the try clause, python executes the statement after the else statement (if there is an else) and then controls the flow through the entire try statement.

Exception handling example 1:
Here is a simple example that opens a file and writes to the contents of the file without an exception:

#!/usr/bin/python
try:
   fh = open("testfile", "w")
   fh.write("This is my test file for exception handling!!")
except IOError:
   print "Error: can't find file or read data"
else:
   print "Written content in the file successfully"
   fh.close()

Output results of the above program:
Written content in the file successfully

Exception handling example 2:
Here is a simple example, which opens a file, writes to the contents of the file, but the file has no write permission, and an exception occurs:
#!/usr/bin/python
try:
   fh = open("testfile", "w")
   fh.write("This is my test file for exception handling!!")
except IOError:
   print "Error: can't find file or read data"
else:
   print "Written content in the file successfully"

Output results of the above program:
Error: can't find file or read data

Use except without any exception type

You can use except without any exception type, as shown in the following example:


try:
   You do your operations here;
   ......................
except:
   If there is any exception, then execute this block.
   ......................
else:
   If there is no exception then execute this block. 

The above try-except statement captures all exceptions that occur. But this is not a good way, we can not identify the specific exception information through the program. Because it catches all exceptions.
Use except with a variety of exception types
You can also use the same except statement to handle multiple exceptions, as shown below:
try:
   You do your operations here;
   ......................
except(Exception1[, Exception2[,...ExceptionN]]]):
   If there is any exception from the given exception list, 
   then execute this block.
   ......................
else:
   If there is no exception then execute this block. 

V. try-finally statement
The try-finally statement executes the final code regardless of whether an exception occurs.
try:
< statements >
finally:
< statements >    # exit try Time will always execute 
raise

Note: you can use either the except or finally statements, but not both. The else statement also cannot be used with the finally statement

Try-finally usage instance:

#!/usr/bin/python
try:
   fh = open("testfile", "w")
   fh.write("This is my test file for exception handling!!")
finally:
   print "Error: can't find file or read data"

If the open file does not have writable permissions, the output is as follows:
The same code at the page code block index 4
The same example can be written as follows:
#!/usr/bin/python
try:
   fh = open("testfile", "w")
   try:
      fh.write("This is my test file for exception handling!!")
   finally:
      print "Going to close the file"
      fh.close()
except IOError:
   print "Error: can't find file or read data"

When an exception is thrown in the try block, the finally block code is executed immediately.
After all the statements in the finally block are executed, the exception is raised again and the except block code is executed.
The content of the parameter is different from that of the exception.

Six, abnormal parameters
An exception can take a parameter, which can be used as the output exception information parameter.
You can catch exception parameters with the except statement, as shown below:

try:
   You do your operations here;
   ......................
except ExceptionType, Argument:
   You can print value of Argument here...

The outliers received by a variable are usually contained in the statement of the exception. Variables can receive one or more values in the form of a tuple.
Tuples usually contain error strings, error Numbers, and error locations.
The following is an instance of a single exception:
#!/usr/bin/python
# Define a function here.
def temp_convert(var):
   try:
      return int(var)
   except ValueError, Argument:
      print "The argument does not contain numbersn", Argument
# Call above function here.
temp_convert("xyz");

The execution results of the above procedures are as follows:
The argument does not contain numbers
invalid literal for int() with base 10: 'xyz'

Raise raises exceptions:
We can use the raise statement to raise the exception ourselves

The syntax of raise is as follows:

raise [Exception [, args [, traceback]]]

The Exception in the statement is the type of the Exception (for example, NameError) and the argument is an Exception parameter value. This parameter is optional; if not provided, the exception parameter is "None".
The last parameter is optional (rarely used in practice) and, if present, is to trace the exception object.
Example of use of raise:
An exception can be a string, class, or object. Most of the exceptions provided by the Python kernel are instantiated classes, which are arguments to an instance of a class.
Defining an exception is as simple as this:
def functionName( level ):
   if level < 1:
      raise "Invalid level!", level
      # The code below to this would not be executed
      # if we raise the exception

Note: in order to catch exceptions, the "except" statement must have the same exception to throw a class object or string.
For example, if we catch the above exception, the "except" statement is as follows:
try:
   Business Logic here...
except "Invalid level!":
   Exception handling here...
else:
   Rest of the code here...

User - defined exception instances
By creating a new exception class, programs can name their own exceptions. Exceptions should typically inherit from the Exception class, either directly or indirectly.
The following example is related to RuntimeError, where a class is created with the base class RuntimeError to output more information when an exception is triggered.
In the try block, the except block statement is executed after the user-defined exception, and the variable e is used to create an instance of the Networkerror class.

class Networkerror(RuntimeError):
   def __init__(self, arg):
      self.args = arg

After you define the above class, you can trigger the exception as follows:
try:
   raise Networkerror("Bad hostname")
except Networkerror,e:
   print e.args


Attachment: python standard exception
BaseExceptiona: the base class for all exceptions
SystemExitb python: the interpreter requests exit
KeyboardInterruptc: user interrupts execution (usually ^C)
Exceptiond: base class for normal errors
StopIteratione: the iterator has no more values
GeneratorExita: generator notifies exit by an exception
SystemExith: Python interpreter requests exit
StandardErrorg: the base class for all built-in standard exceptions
ArithmeticErrord: the base class for all numeric errors
FloatingPointErrord: floating point calculation error
OverflowError: numerical operation exceeded maximum limit
ZeroDivisionError: divide (or modulo) zero (all data types)
AssertionErrord: assertion statement failed
AttributeError: the object does not have this attribute
EOFError: no built-in input, reaches EOF mark
EnvironmentErrord: the base class for operating system errors
IOError: input/output operation failed
OSErrord: operating system error
WindowsErrorh Windows: system call failed
ImportError: failed to import the module/object
KeyboardInterruptf: user interrupts execution (usually ^C)
LookupErrord: the base class for invalid data queries
IndexError: no index in the sequence
KeyError: there is no key in the map
MemoryError: memory overflow error (not fatal to the Python interpreter)
NameError: undeclared/initialized object (no attributes)
UnboundLocalErrorh: accesses an uninitialized local variable
ReferenceErrore: Weak reference attempts to access an object that has been garbage collected
RuntimeError: general RuntimeError
NotImplementedErrord: method not yet implemented
SyntaxError: Python SyntaxError
IndentationErrorg: indentation error
TabErrorg: Tab and space mix
SystemError general interpreter SystemError
TypeError: an operation with an invalid type
ValueError: an invalid parameter is passed in
UnicodeErrorh: unicode-related error
UnicodeDecodeErrori: error while decoding Unicode
Error in UnicodeEncodeErrori: Unicode encoding
UnicodeTranslateErrorf: error while converting Unicode
Warningj: the base class for warnings
DeprecationWarningj: warning about deprecated features
FutureWarningi: warning of future semantic changes in constructs
OverflowWarningk: the old warning about automatic promotion to long integer (long)
PendingDeprecationWarningi: warning about properties will be discarded
RuntimeWarningj: warning of suspicious runtime behavior
SyntaxWarningj: warning of suspicious syntax
UserWarningj: warning generated by user code


Related articles: