Sitemap

Python try except in application

2 min readMay 20, 2026

--

try except is fascinating because, despite internal issues, it prevents the program from crashing.

try:
this()
except:
do_this()

Beginners often do this:

try:
a_task()
except:
pass

Though it prevents the code from crashing, it is not considered best practice in the production code. Because you will not know the issues in the program.

try:
this()
except Exception as e:
print("This is the reason it did not happen:", e)

Python has a built-in function sum() we can add all values in a list.

numbers = [10, 20, 30, 40]
print(sum(numbers))

This works perfectly because all values are valid numbers.

But if even one value is not number, the program will crash:

numbers = [10, 20, "nine", 40]
print(sum(numbers))

This will raise error like:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Now if we try to “protect” it using try/except:

numbers = [10, 20, "nine", 40]

try:
print(sum(numbers))
except Exception as e:
print("Error occurred:", e)

The error is now caught, so the program does not crash, so we now know the issue and can fix it later.

Get Mashiur Rahman’s stories in your inbox

Join Medium for free to get updates from this writer.

Now there is another block finally.

finally always runs, whether there is issue or not.

numbers = [10, 20, "nine", 40]

try:
print(sum(numbers))
except Exception as e:
print("Error occurred:", e)
finally:
print("Execution completed.")

Even if an error happens, the finally block will still execute.

So it is helpful for closing files, releasing resources, and showing messages.

cleaning up a file after reading it.

file = None

try:
file = open("statistics.csv", "r")
content = file.read()

if not content:
raise Exception("File is empty")

print(content)

except Exception as e:
print("Error:", e)

finally:
if file:
file.close()
print("File closed safely.")


Here, even if the file is empty or error occurs while reading, the finally block will ensures the file is always closed properly. Though it used in this example for demonstration but in modern python we can use with open(...) which automatically close the file.

Also you can use else too

Try Except Else Finally

try:
# do the task
except SomeError:
# runs if exception occurs
else:
# runs if NO exception occurs
finally:
# always runs

--

--