finally and raise

In this blog let us consider the Finally and Raise statements that we mentioned in the previous blog.

Finally

The Finally statement executes whether or not there is an error in the code or not. We can use Finally to make sure we clean up the resources that we use. Remember, we can use Try with Finally or Except, in other words, we can use Try and Finally alone.

The syntax for Finally is:

try:

….–line of code–

finally:

….–line of code—

 

Consider an example:

x = 10

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

We have the output as:

Let’s say we have not defined ‘x’, we will get the output as:

Now let’s add a Finally statement to the function we developed which adds 15 to a number given by the user as an input.

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")
finally:
    # Called anytime we use this try block
    print("Error check was completed")

When we run this now, we get:

When we use the wrong input, we get:

Raise

The Raise statement allows us to raise an Exception, which can stop a program. One of the advantages of using Raise is that when we want to validate inputs, we can use Raise. The syntax of using raise is:

  • raise Exception(–some text–)

Consider an example:

value = 17

if value % 5 != 0:
    raise Exception("The value must be a multiple of 5")

We get the result:

We can also use Raise to print a specific Error. Consider a program that takes a user input and adds 100 to it.

input_ = input("Enter a number: ")

if type(input_) is int:
    print(input_ + 100)
else:
    raise ValueError("We cannot add a string and a number")

Let’s give a string as input and see what we get as the output:

What have we learned?

  • How do we use the Finally statement?
  • When is Finally called?
  • How do we use the Raise statement?
  • What is the syntax of Raise?
  • How can we use Raise for a particular error?
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments