Skip to main content

Exception Handling in Python (try - except-else-finally)

Exception Handling in Python

Exception handling is key for any programming language. When an exception occurs Python interpreter stops execution further statements in the program. 

These exceptions could either be related to the Syntax or Data. There are many Built-in exceptions in Python and we can also define user defined exceptions. 

Exception handling in Python can be done by using try - except statements. We can also use else and finally statements depending on how we need to handle the exceptions.

Syntax:

try:

    # Executable statements

except:

    # Statements to execute in case of exception

else:

    # Statements to execute in case of no exception 

finally:

    # Statements to execute irrespective of exception or not


Let's have a look at how to use these statements with few simple examples. 

try and except

try statement should be used in combination of either except or finally. Without these, An exception would occur. 

Let's have a look at the simple division by zero exception (my favorite when it comes to checking exception handling). 

1

2

3

4

a = 10

b = 0

c = a/b

print(c)


Result

Traceback (most recent call last):

  File "/Users/Admin/PycharmProjects/pythonProject/main.py", line 3, in <module>

    c = 10/0

ZeroDivisionError: division by zero



In the above example, 
  • Line - 3: An exception (ZeroDivisionError) is occurred when attempting to divide a with b. 
    • This causes the further statements to not execute. 
We can use try and except statements to handle the exception. 

1

2

3

4

5

6

7

8

try:

   a = 10

   b = 0

   c = a/b

except:

   c = 0

 

print(c)


This is a simple example of handling the exception. 
  • Line - 1: We are using the try statement before the block of code which needs to be monitored for exception. 
    • Lines 2 - 4: Indentation to be followed for the code that should fall under the try statement. 
  • Line - 5: We are using except statement (with no specific exception type) to capture any exception.
    • Line - 6: We are initializing the variable 'c' with zero in case of exception. 
    • This can be replaced with set of statements as required and should follow the indentation. 
  • Line - 8: print statement here would execute with out any error as any exception in the division would be handled with the try and except statements. 

This is a very basic example and we are not using any exception type along with except statement. This would capture all types of exception. 

Let's have a look at different example to open a file and read the content of the file. 

1

2

3

4

notes = open("notes.txt", "r")

notes_content = notes.read()

print(notes_content)

notes.close()


Result


Traceback (most recent call last): File "/Users/Admin/PycharmProjects/pythonProject/main.py", line 1, in <module> notes = open("notes.txt", "r") FileNotFoundError: [Errno 2] No such file or directory: 'notes.txt'


In the above example, we are trying to open a file which does not exist. 
  • Line - 1: An exception is occurred while opening the file which does not exist. 
This causes the following statements to not run. 

Adding try and except statements would capture the error and execute the statements under except block. 

1

2

3

4

5

6

7

try:

   notes = open("notes.txt", "r")

   notes_content = notes.read()

   print(notes_content)

   notes.close()

except:

   print("No file named 'notes.txt'")


In the two examples shared, We are using except statement without mentioning exception type and we are executing different statements for the different exceptions. 

Let's say if the code from both the examples need to be executed as a single block and we need to act based on the exception occurred. 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

try:

   a = 10

   b = 1

   c = a/b

   print(c)

 

   notes = open("notes.txt", "r")

   notes_content = notes.read()

   print(notes_content)

   notes.close()

except ZeroDivisionError:

   c = 0

   print(c)

except FileNotFoundError:

   print("No file named 'notes.txt'")

except:

   print("Error Occurred!")


In the above example, 
  • Lines 1 - 10: try statement followed by the executable statements with the possibility of different exceptions. 
  • Line - 11: We are mentioning 'ZeroDivisionError' along with except statement. This would capture the Division by zero error and runs the block of statements mentioned under this block. 
  • Line - 14: We are mentioning 'FileNotFoundError' along with except statement. This would capture the File not found error and runs the block of statements mentioned under this block.
  • Line - 16: We are using except statement with out any specific exception type. This would capture any error except the two different types of exceptions specifically mentioned. 
Full list of exception types can be found here

else

If there are any set of statements to be executed if no exception occurred, these can be mentioned under the else statement. 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

try:

   a = 10

   b = 1

   c = a/b

   print(c)

 

   notes = open("notes.txt", "r")

   notes_content = notes.read()

   print(notes_content)

   notes.close()

except ZeroDivisionError:

   c = 0

   print(c)

except FileNotFoundError:

   print("No file named 'notes.txt'")

except:

   print("Error Occurred!")

else:

   print("No Error Occurred, Execution is complete!")


In the above example, 
  • Line - 18: We are adding else statement to the try - except. 
    • Block of statements under else would only be executed if the block of code under try is executed without any exception. 

finally

If there are any set of statements to be executed irrespective of the exceptions present or not. These statements can be mentioned under finally statement.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

try:

   a = 10

   b = 1

   c = a/b

   print(c)

 

   notes = open("notes.txt", "r")

   notes_content = notes.read()

   print(notes_content)

   notes.close()

except ZeroDivisionError:

   c = 0

   print(c)

except FileNotFoundError:

   print("No file named 'notes.txt'")

except:

   print("Error Occurred!")

else:

   print("No Error Occurred, Execution is complete!")

finally:

   print("Execution has been completed.")


In the above example, 
  • Line - 20: We are adding finally statement to try - except statements. 
    • Block of statements under finally would be executed irrespective of the exceptions in the code. 

Hope the above info was useful in understanding exception handling in Python. 


If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

Comments

Popular posts from this blog

All about READ in RPGLE & Why we use it with SETLL/SETGT?

READ READ is one of the most used Opcodes in RPGLE. As the name suggests main purpose of this Opcode is to read a record from Database file. What are the different READ Opcodes? To list, Below are the five Opcodes.  READ - Read a Record READC - Read Next Changed Record READE - Read Equal Key Record READP - Read Prior Record READPE - Read Prior Equal Record We will see more about each of these later in this article. Before that, We will see a bit about SETLL/SETGT .  SETLL (Set Lower Limit) SETLL accepts Key Fields or Relative Record Number (RRN) as Search Arguments and positions the file at the Corresponding Record (or Next Record if exact match isn't found).  SETGT (Set Greater Than) SETGT accepts Key Fields or Relative Record Number (RRN) as Search Arguments and positions the file at the Next Record (Greater Than the Key value). Syntax: SETLL SEARCH-ARGUMENTS/KEYFIELDS FILENAME SETGT  SEARCH-ARGUMENTS/KEYFIELDS FILENAME One of the below can be passed as Search Arguments. Key Fiel

What we need to know about CHAIN (RPGLE) & How is it different from READ?

CHAIN READ & CHAIN, These are one of the most used (& useful) Opcodes by any RPG developer. These Opcodes are used to read a record from file. So, What's the difference between CHAIN & READ?   CHAIN operation retrieves a record based on the Key specified. It's more like Retrieving Random record from a Database file based on the Key fields.  READ operation reads the record currently pointed to from a Database file. There are multiple Opcodes that start with READ and all are used to read a record but with slight difference. We will see more about different Opcodes and How they are different from each other (and CHAIN) in another article. Few differences to note.  CHAIN requires Key fields to read a record where as READ would read the record currently pointed to (SETLL or SETGT are used to point a Record).  If there are multiple records with the same Key data, CHAIN would return the same record every time. READE can be used to read all the records with the specified Ke

Extract a portion of a Date/Time/Timestamp in RPGLE - IBM i

%SUBDT Extracting Year, Month, Day, Hour, Minutes, Seconds or Milli seconds of a given Date/Time/Timestamp is required most of the times.  This can be extracted easily by using %SUBDT. BIF name looks more similar to %SUBST which is used to extract a portion of string by passing from and two positions of the original string. Instead, We would need to pass a value (i.e., Date, Time or Timestamp ) and Unit (i.e., *YEARS, *MONTHS, *DAYS, *HOURS, *MINUTES, *SECONDS or *MSECONDS) to %SUBDT.  Valid unit should be passed for the type of the value passed. Below are the valid values for each type. Date - *DAYS, *MONTHS, *YEARS Time - *HOURS, *MINUTES, *SECONDS Timestamp - *DAYS, *MONTHS, *YEARS, *HOURS, *MINUTES, *SECONDS, *MSECONDS Syntax: %SUBDT(value : unit { : digits { : decpos} }) Value and Unit are the mandatory arguments.  Digits and Decimal positions are optional and can only be used with *SECONDS for Timestamp. We can either pass the full form for the unit or use the short form. Below i