Search This Blog

Wednesday, 16 July 2025

Python Basics : Handling Exceptions - Try-Except-Finally

 In Python exceptions can be handled using the try-except-finally block.

This is the most basic way of handling exceptions. The purpose of the try-except-finally block is "Not to expose the internal details of the exception, But present a friendly error message to the End User"

For example, a friendly message as shown here for an internal error of  "Insert into database db-name -> table-name failed View Stacktrace : ....."

⚠️ Something went wrong. Please contact Support at some-email@some-company.


In an enterprise application, try-except-finally are not sufficient.

For every exception handling scenario, there must be two perspectives that should be considered.

1. End user perspective: This is the user who is using your application through a device / browser. He need not know the technicalities and internal workings of this application.

2. The Application Support Team Members: These are the technical staff who would be supporting the end-user in case of any issues faced. This team must have a relevant idea of the internal workings of the product.

Hence, Exception handling can be done using two best practices.

1. For the End-user: We can use the Try-Except-Finally block

2. For the Application Support Team Members: We shall have an additional strategy of using Log files / Log tables


Here, in this article we will understand the flavors of  try-except-finally to present a user-friendly error.

Syntax:


try:
    your code here
except <Error Type>:
    your code here
except <Error Type>:
    your code here
finally:
    your cleanup / closure code



FLAVORS:

Single Except block: Here the error type is Value Error. The base Error type class is known as Exception. To capture errors like key-stroke errors etc, BaseException class can also be used


 Multiple Except Blocks: To catch multiple errors, and return different friendly messages.


Except with Tuple: To return a standard message for multiple error types, add the error types to a tuple.

Catch all types of Exceptions: Use the class Exception / BaseException








No comments:

Post a Comment