Introduction to Python programming to practice (3)

1. Exception

Exceptions are handled using try-except code blocks. A try-except block tells Python what to do when an exception occurs.

When a try-except block is used, the program will continue to run even if there is an exception: display the friendly error message you wrote instead of a traceback that confuses the user.

print(5/0)
Traceback (most recent call last):
  File "exception_division", line 1, in <module>
    print(5/0)
ZeroDivisionError: division by zero

It's not good for your program to crash, nor is it a good idea to let users see the traceback. Malicious users will know the file name of your program and will also see some code that does not work correctly.

 

print("Give me two numbers,and I'll divide them.")
print("Enter 'q' to quit.")

while True:
    first_number=input("\nFirst number: ")
    if first_number == 'q':
        break
    second_number=input("Second number: ")
    if second_number == 'q':
        break
    try:
        answer=int(first_number)/int(second_number)
    except ZeroDivisionError:
        print("You can't divide by 0!")
    else:
        print(answer)
Give me two numbers,and I'll divide them.
Enter 'q' to quit.

First number: 5
Second number: 0
You can't divide by 0!

First number: 5
Second number: 2
2.5

First number: q

This way, the user sees a friendly error message instead of a traceback.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325342658&siteId=291194637