Example: Else and Finally

Well-structured code attempts to identify everything that can go wrong as well as everything that can go right. The "else" and "finally" commands, while optional, are important components of professionally written code. The "else" command can be used as part of a "try-except" block to execute code if no errors in the set of errors being tested have occurred. The "finally" section of code will always run, but it helps to programmatically delineate such code from a software organization perspective to distinguish it from code that is being checked for errors.

What is a try-except block in python?

A try and except block is used for error handling in Python.

  • try: Helps to test the code. If the code inside the try block is error-free it is executed. Otherwise, the error gets caught and control goes to the except block.
  • except: Except displays the error message.
  • else: Executes if there is no error in the code in the try block.
  • finally: Executes independently of the try-except block results.

The else and finally blocks are optional, but it is considered a good programming practice to include them.

 

Type of error messages

There are two types of error that can occur:

  • Syntax Error/Parsing Error: When the Python parser is unable to understand a line of code.
  • Exception: When the error is detected during execution, e.g., ZeroDivisionError.

 

List of exception errors

The following are the list of exception error that arises:

  • IOError: When a file can’t be opened
  • KeyboardInterrupt: When an unrequired key is pressed by the user
  • ValueError: When a built-in function receives a wrong argument
  • EOFError: When one of the built-in functions (input() or raw_input()) hits an end-of-file condition (EOF) without reading any data
  • ImportError: When a module is not found

 

Syntax

The general syntax is:

try:
    statement1 #test code
except:
    statement2 #error message
finally:
    statement3 #must execute 

 

Image of try, catch, finally, block

Try Catch Finally Block

 

Examples

1. Try and except block only

The following code explains how error gets caught in the try block and gets printed in the except block:

  1
  2
  3
  4
  5
try:
  print(variable)
except:
  print("Variable is not defined")
Output:

Variable is not defined

 

2. Try with multiple except blocks

If multiple errors may arise after the execution of one try block, we may use multiple except blocks to handle them.

  1
  2
  3
  4
  5
  6
  7
try:
  print(variable)
except NameError:
  print("Variable is not defined")
except:
  print("Seeems like something else went wrong")
  
Output:

Variable is not defined

Note: It is compulsory that the keyword NameError is written in front of the first except statement.

 

3. Try, except, and else block

The following code explains how else block gets executed when the try executed correctly:

  1
  2
  3
  4
  5
  6
  7
try:
  variable="Python Programming";
  print(variable)
except:
  print("An exception occurred")
else:
  print("Else executes: Try block executed correctly")
  
Output:

Python Programming

Else executes: Try block executed correctly

 

4. Try, except, and finally block

The following code explains how error gets caught in the try block and gets printed in the except block and then the finally block gets executed:

  1
  2
  3
  4
  5
  6
try:
  print(variable)
except:
  print("An exception occurred")
finally:
  print("Always execute this block")
Output:

An exception occurred

Always execute this block


Source: Educative, https://www.educative.io/edpresso/what-is-a-try-except-block-in-python
Creative Commons License This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 License.

Last modified: Tuesday, November 17, 2020, 4:42 PM