This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together

preface

In the writing of code, there are always some bugs and errors, how to capture these exceptions, and processing, to make the program more robust? This article will take you through Python exception handling.

Errors and exceptions

There are at least two possible ways to write a program that is wrong, one is a syntax error, and the other is what we call an exception.

Syntax errors are easy to understand. They are when we write code that does not conform to the Python code specification, causing the program to fail to recognize and run, as in the following example:

Def add(a,b) print(a+b) add(1,2) #SyntaxError: invalid syntaxCopy the code

The function we defined left out the colon, so the error was reported as SyntaxError.

An exception is a ZeroDivisionErro exception that is thrown because there is no error in the programming itself. For example, we all know that 0 cannot be the denominator, so if we take 0 as the denominator, ZeroDivisionErro exception will be thrown.

1/0

# ZeroDivisionError: division by zero
Copy the code

We’re looking at other types of exceptions:

1 + 'a'
# TypeError: unsupported operand type(s) for +: 'int' and 'str'

print(name)
#NameError: name 'name' is not defined
Copy the code

Python, of course, there are many other exception type, you can refer to Python’s official document view (docs.python.org/3/library/e…

Handle exceptions

We all know that when we throw an exception, the whole program will be terminated, but ideally, we want the program not to be terminated, but to catch the exception.

Of course Python has syntax for implementing and handling exceptions, such as try and except.

Except: this code will not run when an exception occurs. As e: This code will run when an exception occursCopy the code

Let’s demonstrate that 0 cannot be the denominator:

Try: a = 1/0 print(a) except ZeroDivisionError as e: print(" error: {}". Format (e)Copy the code

An exception defined in except does not match an exception defined in except. For example:

Except ZeroDivisionError as e: print(" error: {}". Format (e)) # NameError: name' name' is not definedCopy the code

So, this is limited when we have multiple exception errors, we can write it like this:

# the try the first method: print (1/0) print (name) the except (ZeroDivisionError NameError) as e: print (" error: {} ". The format (e)) # try the second method: Print (1/0) print(name) except ZeroDivisionError as e: print(" error: {}". Format (e)) except NameError as e: Print (" error: {}".format(e)) # error: division by zeroCopy the code

The NameError is not caught when the denominator is 0.

This is because when there are more than one except exception, only one exception will be executed and caught. Simply put, the exception caught first will be executed and the rest ignored.

So sometimes we don’t know in advance how many exceptions there are, so how do we deal with that? We can use Exception, which is the base class for other non-system exceptions. Or without an exception class after an except statement block.

Try: print(1/0) print(name) except Exception as e: print(" error: {}". Format (e)) try: print(1/0) print(name) except: Print (" error ")Copy the code

Finally, let’s look at finally, which is used to execute statements in finally with or without exceptions.

try:
    f = open('test.txt','r')
except:
    print('erro')
finally:
    f.close()
Copy the code

Here the file is read and closed regardless of exceptions.

Actively throwing an exception

We can actively raise an exception by using the raise statement: raise followed by the exception to be raised. The exception must be either an exception instance or an exception class.

Then we play a fun thing through raise, 0 can not be the denominator of the exception prompt is In English, I take the initiative to throw an exception, for Chinese prompt.

Try: Raise ZeroDivisionError(' The denominator cannot be zero!! ') except ZeroDivisionError as e: print(' error: {}'.format(e))Copy the code
Custom exception classes

If Python’s built-in exception types do not meet our needs, we can customize the exception class. Note, however, that all built-in non-system exit-class exceptions derive from the Exception class, and all user-defined exceptions should also derive from this class.

Simply put, our own Exception classes must integrate directly or indirectly with the Exception class.

Such as:

class MyError(Exception):
    def __init__(self,value):
        self.value = value
    def __str__(self):
        return '{} is error'.format(repr(self.value))

try:
    raise MyError(1)
except MyError as e:
    print(e)

# 1 is error
Copy the code

Two magic methods: def init(self), the initialization property of the exception class object; Def STR (self) returns the exception class object description.

conclusion
  • Errors and exceptions
  • Exception handling
  • An exception is thrown
  • Custom exception