Home > Backend Development > Python Tutorial > Detailed explanation of python exception handling

Detailed explanation of python exception handling

高洛峰
Release: 2016-10-20 09:46:30
Original
1366 people have browsed it

This section mainly introduces the principles and main forms of exception handling in Python.


1. What is an exception


Exception objects are used in Python to represent abnormal situations. An exception is thrown after a program encounters an error during execution. If the exception object is not handled or caught, the program will backtrack and terminate execution.


2. Throw exception


raise statement, raise followed by Exception exception class or Exception subclass, you can also add exception information in the brackets of Exception.


>>>raise Exception('message')


Note: The Exception class is the base class of all exception classes. We can also create our own defined exception classes based on this class, as follows:


class SomeCustomException(Exception): pass


3. Catching exceptions (try/except statement)


The try/except statement is used to detect errors in the try statement block, so that the except statement can capture exception information and processed.


Multiple exceptions can be thrown in a try statement block:

try:
     x = input('Enter the first number: ')
     y = input('Enter the second number: ')
     print x/y
 except ZeroDivisionError:
     print "The second number can't be zero!"
 except TypeError:
     print "That wasn't a number, was it?"
Copy after login


An except statement can capture multiple exceptions:

try:
     x = input('Enter the first number: ')
     y = input('Enter the second number: ')
     print x/y
 except (ZeroDivisionError, TypeError, NameError):  #注意except语句后面的小括号
     print 'Your numbers were bogus...'
Copy after login

Access the captured exception object and Print out exception information:

try:
     x = input('Enter the first number: ')
     y = input('Enter the second number: ')
     print x/y
 except (ZeroDivisionError, TypeError), e:
     print e
Copy after login

Capture all exceptions to prevent missing unpredictable exceptions:

try:
     x = input('Enter the first number: ')
     y = input('Enter the second number: ')
     print x/y
 except :
     print 'Someting wrong happened...'
Copy after login

4. else clause. In addition to using the except clause, you can also use the else clause. If no exception is thrown in the try block, the else clause will be executed.

while 1:
     try:
         x = input('Enter the first number: ')
         y = input('Enter the second number: ')
         value = x/y
         print 'x/y is', value
     except:
         print 'Invalid input. Please try again.'
     else:
         break
Copy after login

After the above code block is run, if the x and y values ​​entered by the user are legal, the else clause will be executed, allowing the program to exit execution.


5. finally clause. Regardless of whether an exception occurs in the try clause, the finally clause will definitely be executed and can also be used with the else clause. The finally clause is often used to close the file or network socket at the end of the program.

try:
     1/0
 except:
     print 'Unknow variable'
 else:
     print 'That went well'
 finally:
     print 'Cleaning up'
Copy after login

6. Exceptions and functions

If an exception is raised within a function and is not handled, it will be passed to the place where the function is called. If it is not handled, the exception will be passed to the main program and stacked The tracking form is terminated.

def faulty():
    raise Exception('Someting is wrong!')
def ignore_exception():
    faulty()
      
def handle_exception():
    try:
        faulty()
    except Exception, e:
        print 'Exception handled!',e
  
handle_exception()
ignore_exception()
Copy after login

In the above code block, after the function handle_exception() calls faulty(), the faulty() function throws an exception and is passed to handle_exception(), thereby being processed by the try/except statement. There is no exception handling for faulty() in the ignare_exception() function, which causes an exception stack trace.

Note: The conditional statement if/esle can achieve the same function as exception handling, but the conditional statement may be less natural and readable.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template