1. Exceptions
Exceptions are handled using the TRY-EXCEPT code block. The try-except code block lets python perform the specified action and tells Python what to do if an exception occurs.
When you use the TRY-EXCEPT code block, the program continues to run even if an exception occurs: Displays the friendly error messages you wrote, not the traceback that confuse the user.
Print (5/0)
Traceback (most recent): File "Exception_division", line 1, in <module> print (5/0) Zerodivisionerror:division by Zero
The program is bad, let users see Traceback is not a good idea, malicious users will know your program's file name, you will also see some of the code does not run correctly.
Print("Give Me II Numbers,and I ' ll divide them.")Print("Enter ' Q ' to quit.") whileTrue:first_number=input ("\nfirst Number:") ifFirst_number = ='Q': BreakSecond_number=input ("Second Number:") ifSecond_number = ='Q': Break Try: Answer=int (First_number)/Int (second_number)exceptZerodivisionerror:Print("You can ' t divide by 0!") Else: Print(answer)
Give Me II Numbers,and I ' ll divide them. Enter ' Q ' to quit. First Number:5second number:0you can ' t divide by 0! First Number:5second Number:22.5first number:q
In this way, the user sees a friendly error message, not a traceback.
Getting started with Python programming to Practice (iii)