【Python】Basics - Exceptions

Posted by 西维蜀黍 on 2019-09-18, Last Modified on 2024-05-07

Using try-except Blocks

When you think an error may occur, you can write a try- except block to handle the exception that might be raised. You tell Python to try running some code, and you tell it what to do if the code results in a particular kind of exception.

Here’s what a try- except block for handling the ZeroDivisionError exception looks like:

try:
		print(5/0) 
except ZeroDivisionError:
		print("You can't divide by zero!")

The else Block

Note: If there is no any exception thrown, code in the else block will be executed.

Any code that depends on the try block executing successfully goes in the else block:

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: ") 
	try:
		answer = int(first_number) / int(second_number) 
	except ZeroDivisionError:
		print("You can't divide by 0!") 
	else:
		print(answer)

We ask Python to try to complete the division operation in a try block, which includes only the code that might cause an error. Any code that depends on the try block succeeding is added to the else block. In this case if the division operation is successful, we use the else block to print the result.

The except block tells Python how to respond when a ZeroDivisionError arises. If the try statement doesn’t succeed because of a division by zero error, we print a friendly message telling the user how to avoid this kind of error.

Reference

  • Python Crash Course (2nd Edition) : A Hands-On, Project-Based Introduction to Programming
  • Learning Python