Python Try Except

Updated: April 23rd, 2023, 08:50:41 IST
Published: April 23rd, 2023
Python Try Except
Title: Python Try Except

In programming, errors or exceptions can occur during runtime that can halt the program's execution. To handle such errors gracefully, Python provides the try-except statement. This statement allows the programmer to write code that can detect and respond to errors, thus preventing the program from crashing. In this blog, we will explore the try-except statement in Python, how it works, and some examples to illustrate its usage.

In Python, the try-except statement is used to handle exceptions or errors that might occur while running a block of code. Here are the key parts of this statement:

  1. try block: This block of code is used to test a specific piece of code that could potentially raise an exception. If an exception occurs in this block, the program will move to the except block.
  2. except block: This block of code is used to handle the exception that occurred in the try block. You can specify the type of exception you want to handle. If no exception type is specified, the except block will handle all exceptions.
  3. else block: This block of code is executed if there is no exception raised in the try block.
  4. finally block: This block of code is executed whether or not an exception occurred. It is useful for releasing resources like files or network connections.

Here's an example of how to use these blocks in a simple way:

try:
    # code that might raise an exception
except ExceptionType:
    # handle the exception of type ExceptionType
else:
    # code that will be executed if no exception occurs
finally:
    # code that will be executed whether an exception occurred or not

In short, the try-except statement is used to handle exceptions that might occur in a block of code. The except block is used to handle the exception, the else block is executed if no exception occurred, and the finally block is executed regardless of the result of the try and except blocks.

How does Try-Except work?

The try-except statement allows the programmer to write code that can detect and respond to errors. The general syntax of try-except is as follows:

try:
    # block of code to be attempted
except ExceptionType:
    # block of code to be executed if an exception of type ExceptionType is raised

When writing code, there are situations where something unexpected might happen, such as trying to divide a number by zero or trying to access a file that doesn't exist. These situations can cause an error or exception which can cause the program to stop working.

To prevent this from happening, we can use a try-except statement. We place the code that we think might cause an exception inside the try block. If an exception occurs, instead of the program crashing, it will jump to the except block where we can write code to handle the exception.

For example, let's say we have a program that asks the user to enter their age. We can use a try-except statement to handle the situation where the user enters something other than a number.

try:
    age = int(input("Please enter your age: "))
except ValueError:
    print("You did not enter a valid number for your age.")

This code asks the user for their age and converts it to an integer using a try block. If the user enters something that cannot be converted to an integer, a ValueError exception is raised and the except block prints a message to the user. If any other type of exception occurs, the program crashes.

We can also use the except block to handle multiple types of exceptions by separating them with a comma, like this:

try:
    # code that might raise an exception
except (ExceptionType1, ExceptionType2):
    # handle the exceptions of type ExceptionType1 and ExceptionType2

Example 1: Handling a Division by Zero Error

Let's look at an example to illustrate the usage of try-except. Consider the following code that divides two numbers:

a = 10
b = 0
result = a/b
print(result)

If we run this code, we will get a ZeroDivisionError since we are trying to divide a number by zero. To handle this error, we can use try-except as follows:

a = 10
b = 0
try:
    result = a/b
    print(result)
except ZeroDivisionError:
    print("Division by zero is not allowed.")

In this code, we put the division operation inside a try block. If the division operation raises a ZeroDivisionError, the program jumps to the except block, which prints a message stating that division by zero is not allowed.

Example 2: Handling a File Not Found Error

Another common use case for try-except is handling file operations. Let's consider the following code that tries to open a file:

filename = "nonexistentfile.txt"
with open(filename) as f:
    content = f.read()
    print(content)

If we run this code, we will get a FileNotFoundError since the file does not exist. To handle this error, we can use try-except as follows:

filename = "nonexistentfile.txt"
try:
    with open(filename) as f:
        content = f.read()
        print(content)
except FileNotFoundError:
    print(f"File '{filename}' not found.")

In this code, we put the file operations inside a try block. If the file operation raises a FileNotFoundError, the program jumps to the except block, which prints a message stating that the file was not found.

Example 3: Handling Multiple Exceptions

When we use a try-except statement, we can also handle multiple exceptions in the same except block. This can be useful when we want to handle different types of exceptions in the same way. Here's an example:

try:
    file = open('myfile.txt')
    line = file.readline()
    number = int(line)
    result = 100 / number
    file.close()
except (FileNotFoundError, ValueError, ZeroDivisionError):
    print("An error occurred while processing the file.")

In this code, we try to open a file called "myfile.txt", read the first line, convert it to an integer, and then divide 100 by the number. This code may raise three types of exceptions: FileNotFoundError if the file doesn't exist, ValueError if the first line of the file is not a number, and ZeroDivisionError if the number is zero.

We handle all of these exceptions in the same way in the except block, by printing a message to the user that an error occurred while processing the file.

Note that we can also handle each type of exception in a separate except block if we want to handle them differently:

try:
    file = open('myfile.txt')
    line = file.readline()
    number = int(line)
    result = 100 / number
    file.close()
except FileNotFoundError:
    print("The file could not be found.")
except ValueError:
    print("The first line of the file is not a number.")
except ZeroDivisionError:
    print("Cannot divide by zero.")

In this code, we handle each type of exception in a separate except block and print a different message to the user for each type of exception.

In summary, when we use a try-except statement, we can handle multiple types of exceptions in the same except block, or handle each type of exception in a separate except block. This allows us to handle different types of exceptions in different ways.

Raise an Exception

In Python, we can also manually raise an exception using the raise keyword. This is useful when we want to signal an error in our code, without waiting for it to happen naturally.

For example, let's say we are writing a function that takes a number as an argument and we want to make sure that the number is positive. We can manually raise a ValueError exception if the number is not positive:

def check_positive(number):
    if number <= 0:
        raise ValueError("Number must be positive.")
    else:
        print("Number is positive.")

check_positive(5)    # Output: Number is positive.
check_positive(-2)   # Output: ValueError: Number must be positive.

In this code, we define a function check_positive that takes a number as an argument. We use an if statement to check if the number is positive. If it is not, we raise a ValueError exception with a custom message using the raise keyword. If the number is positive, we print a message.

When we call the function with a positive number, it prints "Number is positive." If we call the function with a negative number, a ValueError exception is raised with the message "Number must be positive."

Manually raising an exception can be useful in situations where we want to stop the execution of our code and signal an error. By raising an exception, we can provide more information about the error to the user, which can help with debugging.

Try Except Conclusion

In conclusion, the try-except statement is a powerful tool in Python that allows us to handle exceptions in our code. It lets us write code that can gracefully handle errors and prevent our program from crashing.

By using a try block to contain the code that might raise an exception, and an except block to handle the exception, we can provide a fallback mechanism that keeps our program running in the face of unexpected situations.

We can also use the else and finally blocks to add additional functionality to our exception handling code, such as running code only when there is no exception, or running code regardless of whether there is an exception.

Overall, the try-except statement is an essential tool in writing robust and reliable Python code. It enables us to catch and handle exceptions, providing better control over the flow of our programs and improving the overall user experience.