Python learning exception

Source: Internet
Author: User

Python learning exception

#============================ Common exceptions ============== ==============
# Print (a); # NameError: name 'A' is not defined variable undefined
# If True: # SyntaxError: unexpected EOF while parsing syntax error
# F = open ("123.txt"); # FileNotFoundError: [Errno 2] No such file or directory: '123.txt 'does not have this file # print (10/0 );
# ZeroDivisionError: the division by zero division is 0. # print (int (""));
# ValueError: invalid literal for int () with base 10: 'A' value conversion is invalid
#-*-Config = UTF-8-*-# ================================ Exception Handling (capture runtime exceptions) ================================## Common exceptions # print (a); # NameError: name 'A' is not defined variable undefined # if True: # SyntaxError: unexpected EOF while parsing Syntax Error # f = open ("123.txt"); # FileNotFoundError: [Errno 2] No such file or directory: '123.txt 'does not have this file # print (10/0); # ZeroDivisionError: division by zero division is 0 Error # print (int ("a"); # ValueError: invalid literal for int () With base 10: the 'A' value conversion is invalid #============================= try-another t syntax ========== =========== def tryTest_1 (): try: print (10/0); catch t: # capture all types of exceptions print ("Zero Error"); # Zero Error # tryTest_1 (); def tryTest_2 (): try: print (10/0); counter t ZeroDivisionError as e: # capture the exception print ("Zero Error") of the specified type; # Zero Error # tryTest_2 (); # case-based game import random; def guessNum (): num = random. randint (0,100); # generate a random number while True: try: inputNu M = int (input (); counter t ValueError as e: print ("enter a number from 1 to"); continue; if num> inputNum: print ("input too small"); if num <inputNum: print ("input too large"); if (num = inputNum): print ("OK"); break; # guessNum (); #======================================================= ========= def tryTest_3 (): try: f = open ("2.txt"); cannot t FileNotFoundError as e: print (" file does not exist "); # file does not exist except T ValueError as e: print ("wrong value"); # tryTest_3 () ;#========================== ===== Try-Modify T-else ==================## if the Exception Code is caught, if no exception occurs, run elsedef tryTest_4 (): try: print (1 + 1); # f = open ("2.txt"); alias t FileNotFoundError as e: print ("file does not exist"); # file does not exist. t ValueError as e: print ("wrong value"); else: print ("No Error"); # tryTest_4 (); #================================== try finally ==================## whether or not to check to exception, will Execute finally Code # function: provides a clearing Mechanism for exception handling events to close files or release resources. Def tryTest_5 (): try: f = open ("2.txt"); finally: print (" file close "); f. close (); # tryTest_5 (); #===================================== try-try t-finally ============ = #1. If no exception is caught in the try statement, after the try code is executed, run the finally statement #2. if an exception is caught in the try statement, run the explain T statement first and then run the finally statement def tryTest_6 (): try: f = open ("2.txt"); alias t FileNotFoundError as e: print (" file does not exist "); finally: print (" file close "); f. close (); # tryTest_6 (); #===================================== try-else t-else-finally ====== ========## 1. If the try statement does not catch exceptions, run the try code and then execute the else statement and finally execute the finally statement #2. If the try statement captures an exception, first execute the finally t statement and then execute the finally statement def tryTest_7 (): try: print (10/1); counter t ZeroDivisionError as e: # capture an exception of the specified type print ("Zero Error"); # Zero Error else: print ("else statement"); finally: print ("finally"); # tryTest_7 (); #================================ with statement ========== ================## Replace the try-again t-finall statement with the with statement to make the code more concise def withTEst (): try: with open ("E: \ python \ w_2.txt") as f: print (f. readline (); character t FileNotFoundError as e: print ("file does not exist"); f. close (); # withTEst (); #=================================== raise statements ==================== ==================## raise actively throws an exception # similar to the throw keyword def raiseTest () in java (): raise IOError ("IO exception"); # raiseTest (); #================================== assert statement ====================== ==========================## assert statement: it is used to check whether the expression is true. If the expression is false, an AssertionError error is thrown. # Syntax: assert expression (determining an expression) # assert expression1, expression2 (determining multiple expressions) import random; def assertTest (n): assert n> random. randint (0, 10); print (n); # assertTest (3 ); # If the input n is greater than the number of randomly generated records, print n # If the input n is less than the number of randomly generated records, the AssertionError is thrown.

 

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.