Level 1
0 / 100 XP

Try, Except

Hello there! In this lesson, we're going to learn about the try, except, else, and finally keywords in Python.

The try keyword is used to define a block of code that will be executed and potentially raise an error. If an error is raised, the code inside the except block will be executed to handle the error. Here's an example of how try and except can be used in Python:

Python
try: # Some code that might raise an error 1 / 0 except ZeroDivisionError: # Code to handle the error print("You cannot divide by zero!")

In this code, we use the try keyword to define a block of code that attempts to divide 1 by 0. Since this operation is not allowed, it will raise a ZeroDivisionError.

We use the except keyword to define a block of code that will be executed if a ZeroDivisionError is raised. In this case, the code inside the except block prints the message "You cannot divide by zero!" to the screen.

The else keyword can be used in conjunction with try and except to define a block of code that will be executed only if no errors are raised in the try block. Here's an example that uses try, except, and else:

Python
try: # Some code that might raise an error 1 / 1 except ZeroDivisionError: # Code to handle the error print("You cannot divide by zero!") else: # Code to be executed if no errors are raised print("The operation was successful!")

In this code, we use the try keyword to define a block of code that divides 1 by 1. Since this operation is allowed, no errors are raised, and the code inside the else block is executed. In this case, the code inside the else block prints the message "The operation was successful!" to the screen.

Finally, the finally keyword can be used in conjunction with try and except to define a block of code that will be execut…