Skip to main content

"Try/Except" and "Try/Except/Finally" statements in python

        In Python — along with most other languages — we use try statements to safeguard our code.

Let’s learn about what try statements do and how to begin using them!

What are Exceptions?
Before we dive into the syntax and implementation of try statements, it’s important to establish what exceptions are. 
An exception is the result of code within a try statement that fails. Think of an exception as your code being insulted — “I take exception to that request!”
There are a variety of exception types, we’ll be introduced to a few of them through this tutorial.

How to Use Try Statements?

A try statement, often referred to as a try block, in fact consists of at least two parts: try and except. 

The code we want to safeguard goes inside the try portion of the block. Afterwards, we define what happens when something goes wrong within the except.

In the example above, we use the catch-all value Exception to route any exception to this portion of the block. We also print a vague
message. But what if we want the actual error message from Python?

You can define multiple except blocks within a try, specifying the exact type of exception that should be routed to each. Additionally, you can set the error message to a variable—e is common—so it can be used in your program.

Now we’re in business! Our code is safeguarded, organised, and easily extended.

Let’s see what this looks like in a while loop tasked with collecting an integer input.

The Different Try/Except Variations

So far we’ve used a try/except and even a try/except/except, but this is only two-thirds of the story.

There are two other optional segments to a try block: else and finally. Both of these optional blocks will come after the try and the except. Also, there’s nothing stopping you from using both else and finally in a single statement — but keep them in that order if you do.

Let’s go through each individually and see how they extend the behaviour of a simple try/except.


When attaching an else statement to the end of a try/except, this code will be executed after the try has been completed, but only if no exceptions occur.

We can take the previous example of prompting a user for an integer input and use an else block to thank them for valid input and breaking out of the while loop.


When attaching a finally statement to the end of a try/except, this code will be executed after the try has been completed, regardless of exceptions.

Again, we’ll use our previous example and add a simple counter to illustrate this behaviour.

This might look a bit odd because the break is still inside the try. It’s reasonable to think that the finally would be cut short upon proper input, however, that’s not the case. The finally section will still execute, regardless of how the try is exited.


Popular posts from this blog

CRUD operations using Flask and SQLAlchemy

Every database-related application has to deal with CRUD operations. It is used to store and retrieve data from the database. The CRUD operations are,
CreateInsertUpdateDeleteSQLAlchemy provides us a method to perform the CRUD operations. We can see this with the help of the book table. The book model looks like this.

Inserting the recordsNew records can be inserted by following these three steps. They are Create the python objectAdd it to the sessionCommit the session ExampleData can be inserted into the book model by the following commands.

Deleting the records
Deleting the records is very similar to adding the records. Instead of using the session.add(), we will use session.delete(), and commit the changes.

Querying the database
Flask-SQLAlchemy provides a query attribute on model class. Querying refers to the action of retrieving data from the database. For example, we may need only the people living in a particular city or from a particular age group. For these purposes querying come…

Python program to count the number of occurrences of a letter in a word or in a sentence

Suppose if we want to count the number of occurrences of a letter in a word or in a sentence, we can use the count function from python.

This is the sample code. I am assigning a string to the variable called text. Then i am counting the number of 'e' in the text.

This code produces an output of 8.

Python String count() 

The string count() method returns the number of occurrences of a substring in the given string. In simple words, count() method searches the substring in the given string and returns how many times the substring is present in it.

 It also takes optional parameters start and end to specify the starting and ending positions in the string respectively.

 The syntax of count() method is: 

string.count(substring, start=..., end=...)By providing the start value the function searches for the substring only after the start index.

If an end value is given the function searches until the end of this index.


In this example there is a list consisting of different words. I wi…

Map function in python [map()]

Map function is a good alternative for the “for loops” in python. Sometimes we do not want our code to look clumsy because of all the for loops we have used. In this case the “map()” in python comes to the rescue.
What are map functions?

map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.)


map(fun, iter)

map() Parameter
function - map() passes each item of the iterable to this function.iterable iterable which is to be mapped
You can pass more than one iterable to the map() function.

The map() function applies a given to function to each item of an iterable and returns a list of the results.
The returned value from map() (map object) then can be passed to functions like list() (to create a list), set() (to create a set) and so on.

Map function with a list

In this example there is a single list called numbers and a function square. The map function iterates the list one by one, passes t…