try and except

Let us look at an example of a program that adds 15 to the user’s input.

def add_function(number):
    print(type(number))
    print("")
    number = int(number)
    print(number + 15)

user_input = input("Enter a number: ")
add_function(user_input)

The program must convert the user’s input into an integer type, as the type of the value stored in the variable is a String. Supposing the user entered a string instead of a number, the program would simply crash.

Let’s consider the try, except, and else statements to see how we can modify our code to run correctly even if there is something faulty. 

In this blog we will focus on the Try, Except, and Else statements and in the next blog we will cover the Finally and Raise statements.

Try & Except Statement

The Try statement allows us to test a block of code for any potential errors it may have. It is mandatory to include an Except or Finally statement with Try. Except allows us to handle the errors if we faced an error within Try.

The syntax for Try and Except is:

try:

….–line of code–

except:

….–line of code–

Consider an example:

try:
    print(x)
except:
    print("The code has some error")

Here we are trying to print the value of a variable ‘x’ without even defining it. However, since we used the Try and Except statement it will run the code in Try and since there is an error it will jump over to Except block and execute our code from there. So, when we run our code, we get:

Consider our earlier example and let us use Try and Except so that our code will conclude correctly.

def add_function(number):
    try:
        print(type(number))
        print("")
        number = int(number)
        print(number + 15)
    except:
        print("You did not enter a number")

user_input = input("Enter a number: ")
add_function(user_input)

We get this as the result:

An alternative way of writing the above code would be:

def add_function(number):
    print(type(number))
    print("")
    number = int(number)
    print(number + 15)

user_input = input("Enter a number: ")

try:
    add_function(user_input)
except:
    print("You did not enter a number")

This would still give us the same output as the above code snippet. The difference is that in the first approach we checked for an error within the function itself and in the second approach we checked for an error while calling the function.

We can advance our usage of the Except statement by asking Python to check for specific errors or ‘Exceptions’ and print an error message following it. In the above example, the error produced without the Try Except statements is a ‘ValueError’. So, we can modify our code as shown:

def add_function(number):
    print(type(number))
    print("")
    number = int(number)
    print(number + 15)

user_input = input("Enter a number: ")

try:
    add_function(user_input)
except ValueError:
    # Covers only a value error
    print("You did not enter a number")
except:
    # Covers all other errors
    print("Something else has gone wrong")

Now if the code fails due to an invalid input, the first except statement will be executed, however, if there is some other failure instead of abruptly ending the program the code in the second except statement will be executed. This allows us to be more concise in generating reports of where our code went wrong. Using the vast list of exceptions available we build a more complex program that can generate useful reports if our code fails.

Else Statement

This statement allows us to have some line of code executed if and only if there was no error when executing our code. In a real-world scenario, we can use this to only upload some information to our website only if the entered information is valid.

Consider an example:

x = 10

try:
    print(x)
except:
    print("The code has some error")
else:
    print("Printed without any errors")

This gives us the output:

Let’s add an Else statement to our earlier example:

def add_function(number):
    print(type(number))
    print("")
    number = int(number)
    print(number + 15)

user_input = input("Enter a number: ")

try:
    add_function(user_input)
except ValueError:
    # Covers only a value error
    print("You did not enter a number")
except:
    # Covers all other errors
    print("Something else has gone wrong")
else:
    print("There were no errors in this computation")

Let’s run this code two times to see what would be the output for the correct user input as well as the incorrect user input.

  1. Right user input

The Else statement was executed.

  1. Wrong user input

The Else statement was not executed.

 

What have we learned?

  • What does the Try statement do?
  • What does the Except statement do?
  • What is the syntax of using a Try statement?
  • How can we use Except to generate accurate reports in the case of an error?
  • What does the Else statement do?
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments