Lesson 17 of 30
In Progress

Try and Except Statements

In Python, try and except statements allow you to handle errors and exceptions in your code. When an error or exception occurs, it can cause your program to crash or behave unexpectedly. Using try and except statements allows you to anticipate and handle these errors and exceptions in a controlled manner, so that your program can continue to run without crashing.

Here is an example of a try and except statement in Python:

try:
    # code that may cause an error or exception
except ExceptionType:
    # code to handle the error or exception

The code within the try block is the code that may cause an error or exception. If an error or exception occurs, the program will jump to the except block and execute the code within it. The “ExceptionType” specifies the type of error or exception that the except block should handle.

For example, consider the following code:

try:
    num1 = int(input("Enter a number: "))
    num2 = int(input("Enter another number: "))
    result = num1 / num2
except ZeroDivisionError:
    print("Cannot divide by zero!")

In the above example, the try block contains code that prompts the user to enter two numbers and divides the first number by the second number. If the second number is zero, a ZeroDivisionError will occur. The except block handles this error by printing a message indicating that the division by zero is not allowed.

“else” Keyword

You can also use the “else” keyword to specify a block of code that should be executed if no errors or exceptions occur within the try block. For example, consider the following code:

try:
    num1 = int(input("Enter a number: "))
    num2 = int(input("Enter another number: "))
    result = num1 / num2
except ZeroDivisionError:
    print("Cannot divide by zero!")
else:
    print(f"The result is {result}")

In the above example, the “else” block contains code that prints the result of the division if no errors or exceptions occur.

“finally” Keyword

You can also use the “finally” keyword to specify a block of code that should always be executed, regardless of whether an error or exception occurs within the try block. For example, consider the following code:

try:
    num1 = int(input("Enter a number: "))
    num2 = int(input("Enter another number: "))
    result = num1 / num2
except ZeroDivisionError:
    print("Cannot divide by zero!")
else:
    print(f"The result is {result}")
finally:
    print("The try and except block has finished executing.")

In the above example, the “finally” block contains code that prints a message indicating that the try and except block has finished executing.

Conclusion

Try and except statements are an important tool for handling errors and exceptions in Python, and allow you to write more robust and reliable code.

As you continue to learn and develop your Python skills, you will encounter many other types of errors and exceptions, and it is important to understand how to use try and except statements to handle them in a controlled manner.

Exercises

Here are some exercises with solutions to help you practice what you just learned:

What is the purpose of try and except statements in Python?

The purpose of try and except statements in Python is to handle errors and exceptions in a controlled manner, so that the program can continue to run without crashing.

How do you specify the type of error or exception that an except block should handle in Python?

To specify the type of error or exception that an except block should handle in Python, you use the name of the error or exception type as the argument to the except keyword. For example:

try:
    # code that may cause an error or exception
except ZeroDivisionError:
    # code to handle a ZeroDivisionError

In the above example, the except block handles a ZeroDivisionError.

How do you specify a block of code that should be executed if no errors or exceptions occur within a try block in Python?

To specify a block of code that should be executed if no errors or exceptions occur within a try block in Python, you use the “else” keyword followed by a colon and the code that you want to execute. For example:

try:
    # code that may cause an error or exception
except ExceptionType:
    # code to handle the error or exception
else:
    # code to be executed if no errors or exceptions occur

How do you specify a block of code that should always be executed, regardless of whether an error or exception occurs within a try block in Python?

To specify a block of code that should always be executed, regardless of whether an error or exception occurs within a try block in Python, you use the “finally” keyword followed by a colon and the code that you want to execute. For example:

try:
    # code that may cause an error or exception
except ExceptionType:
    # code to handle the error or exception
else:
    # code to be executed if no errors or exceptions occur
finally:
    # code to be always executed

How do you raise an exception manually in Python?

To raise an exception manually in Python, you use the “raise” keyword followed by the exception type and a message. For example:

raise ValueError("Invalid input")

In the above example, a ValueError exception is raised with the message “Invalid input”.

Raising exceptions manually can be useful when you want to handle error cases in your code in a specific way. For example, you might raise an exception if the user enters invalid input, or if a function is called with inappropriate arguments.