Python bit record 12: Exception handling

Source: Internet
Author: User

The exception handling mechanism is introduced so that the running program does not crash when an error occurs.

Common formats:

Try:command 1except:command 2

When command 1 performs an error, command 2 is executed. Command 2 is usually a self-defined error message or a system default prompt.

eg

#!/usr/bin/pythonwhile 1:        c = raw_input ("Input   ' C '  continue,otherwise logout: ")         if c  ==  ' C ':                 a = raw_input ("Input first number:")                  b = raw_input ("Input second number:")                 try:                          print float (a)/float (b)                          print  "+ + ++++++++++++++++++ "  &nbSp;             except zerodivisionerror :                         print  "The second number can ' t be zero!"                          print  "++++++++++++++++++++"                  except ValueError:                          print  "Please input number."                          print  "++++++++++++++++++++"         else:                 break

The first except or the second except statement is executed when the second entered by the user is 0 or is not a number.


Other formats:

Try:command 1except:command 2else:command 3

When command 1 is executed successfully, command 3 is executed and command 2 is not executed. If command 1 executes an exception, then command 2 is executed, and command 3 is not executed.


Try:command 1except:command 2else:command 3finally:command 4

In this format, finally (Command 4) is always executed regardless of which statement is executed.

Python bit record 12: Exception handling

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.