Python’s Built-in Exceptions and Try-Except Block

You know how sometimes you write some code that looks perfect on paper but when it runs, it throws an error? Well, that’s where these guys come in to save the day!

To set the stage: what are exceptions? They’re basically errors that occur during program execution and can cause unexpected behavior or even crash your entire application. But don’t freak out Python has a way for you to handle them gracefully using try-except blocks.

Here’s how it works: you wrap the code that might throw an error in a try block, and if an exception is raised (i.e., something goes wrong), Python jumps directly to the except block instead of crashing your program. The statements inside this block can provide a remedy for the error or handle it gracefully.

Let’s take a look at some examples:

# Import the sys module to access command line arguments
import sys

# Use a try-except block to catch any potential errors
try:
    # Convert the first command line argument to a float and assign it to the variable C
    C = float(sys.argv[1])
except:
    # If an error occurs, print a message and exit the program with a non-zero status code
    print('You failed to provide Celsius degrees as input on the command line!')
    sys.exit(1)

# Calculate the Fahrenheit equivalent of the input Celsius degrees and assign it to the variable F
F = 9.0*C/5 + 32

# Print the result in a formatted string, including the original Celsius input and the calculated Fahrenheit value
print('%gC is %.1fF' % (C, F))

In this example, we use the sys module to access command line arguments and convert them into a float value for Celsius degrees. If an error occurs during this conversion (e.g., if no argument was provided), Python jumps directly to the except block where we print an error message and exit with a non-zero status code using `sys.exit(1)`.

Another example:

# This script takes command line arguments and converts them into Celsius degrees

# Import the sys module to use the sys.exit() function
import sys

# Use the try-except block to handle potential errors
try:
    # Use the float() function to convert the first command line argument into a float value
    celsius = float(sys.argv[1])
# If an error occurs during the conversion, jump to the except block
except IndexError:
    # Print an error message
    print("No argument provided!")
    # Exit the script with a non-zero status code
    sys.exit(1)
except ValueError:
    # Print an error message
    print("Invalid argument provided!")
    # Exit the script with a non-zero status code
    sys.exit(1)

# Calculate the Fahrenheit equivalent of the Celsius value
fahrenheit = (celsius * 9/5) + 32

# Print the result
print("{} degrees Celsius is equal to {} degrees Fahrenheit.".format(celsius, fahrenheit))

In this example, we use a try-except block to handle the case where the specified file cannot be found (i.e., `FileNotFoundError`). If no error occurs during opening and reading the file, Python executes the statements inside the else block. Finally, regardless of whether an exception occurred or not, Python always executes the statements inside the finally block in this case, closing the file to ensure that it’s properly released after use.

With try-except blocks and built-in exceptions, your code can handle errors gracefully instead of crashing unexpectedly.

SICORPS