Methods of exception handling and debugging in python
This article mainly introduces "the method of python exception handling and debugging". In the daily operation, I believe that many people have doubts about the method of python exception handling and debugging. The editor consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "python exception handling and debugging methods". Next, please follow the editor to study!
Foreword:
An exception is a behavior that can be taken outside the normal control process when an error occurs.
1. Try-except
Try: age = int (input ("Please enter your age:") if age > = 18: print ("you are an adult") else: print ("you are a minor") except ValueError as error: print ("illegal input") print (error) print ("Program ends")
Please enter age: abc
Illegal input
Invalid literal for int () with base 10: 'abc'
End of program
II. Try-except-else
If the except is not executed without exception, the statement in else is executed.
Try: age = int (input ("Please enter Age:") except ValueError as error: print ("illegal input") else: if age > = 18: print ("you are an adult") else: print ("you are a minor") print ("Program ends")
Please enter age: a
Illegal input
End of program
III. Try-except-finally
Finally must be executed regardless of whether an exception occurs, such as closing a file
Try: file = open ("text.txt", "w") # Open file s = "hello world" file.write (s) # Operation file except: print ("operation exception") finally: # execute file.close () # close file print ("close file") 4. Handle multiple exceptions
Method 1:
Try: age = int (input ("please enter age:") x = 10 / ageexcept ValueError: print ("Please enter an integer") except ZeroDivisionError: print ("age cannot be 0") else: print (f "age is {age}") print (f "x is {x}")
Method 2:
Try: age = int (input ("please enter age:") x = 10 / ageexcept (ValueError, ZeroDivisionError): print ("Please enter a reasonable age") else: print (f "age is {age}") print (f "x is {x}") 5. Raise actively throws an exception
In the try statement, an exception is thrown only when an exception is encountered
Raise is to actively throw an exception.
Def is_adult (age): if age < 18: raise ValueError ("you are a minor") try: age = int (input ("Please enter your age:) is_adult (age) # has been thrown