Exception handling in python using try, except and finally statement



Introduction

Why is exception handling in python so important? indeed it is very important in almost all programming languages. Well, to understand its importance you need to understand two types of errors that you encounter while coding:

  1. Syntax (Parsing) errors
  2. Exceptions
Syntax Error

Syntax errors are identified at compile-time, before running the script. A syntax error occurs when programmers do not follow python syntax.

Example:

for i in range(5)    # semi-colon is missing

Error:

SyntaxError: invalid syntax

Exceptions

Exception handling in python; Exceptions are run-time errors. Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not unconditionally fatal. Most exceptions are not handled by programs such as,

Example 1:

print(5/0)

Exception:

ZeroDivisionError: division by zero


Example 2:

print(5 + '5')

Error:

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

Note: Exceptions come in different types, and the type is printed as part of the message: the type of exceptions in the above example are ZeroDivisionError and TypeError.  The string printed as the exception type is the name of the built-in exception that occurred. This is true for all built-in exceptions, but need not be true for user-defined exceptions (although it is a useful convention). Standard exception names are built-in identifiers (not reserved keywords).



Exception handling in python

An exception can be handled in such a way that the entire execution of the script is not stopped since it happens during run-time. To do this, we will use a try-except block for exception handling.

Example:

while True:
    a = 10
    b = int(input("Enter number b: "))
    try:
        c = a/b
        print(f"c={c}")
        break
    except:
        print("Exception occurred! ")

Output:

Enter number b: 0
Exception occurred!
Enter number b: 5
c=2.0
Handling pre-defined Built-in Exceptions

Python has built-in exceptions generated by interpreters or by built-in functions. The try and except statement also has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception.

The example below demonstrates how to handle built-in exceptions with else clause:

a = 10
b = int(input("Enter number b:"))
try:
    c = a/b
except ZeroDivisionError as e:
    print("Division by Zero is not allowed. Exception raised: ",e)
except Exception as e:
    print("Unspecified error occurred. Exception raised: ",e)
else:
    print("Program executed successfully!")
    print("A divided by b:", c)

Output:

Enter number b: 0
Division by Zero is not allowed. Exception raised: division by zero

Note:

The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try except statement.

The try statement works as follows.

  • First, the try clause (the statement(s) between the try and except keywords) is executed.
  • If no exception occurs, the except clause is skipped and execution of the try statement is finished.
  • If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.
  • If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with an exception message.
  • A try statement may have more than one except clause, to specify handlers for different exceptions.


Defining clean-up action

The try statement has another optional clause known as finally which is intended to define clean-up actions that must be executed under all circumstances. If a finally clause is present, the finally clause will execute as the last task before the try statement completes. The finally clause runs whether or not the try statement produces an exception. The following points discuss more complex cases when an exception occurs:

  • If an exception occurs during execution of the try clause, the exception may be handled by an except clause. If the exception is not handled by an except clause, the exception is re-raised after the finally clause has been executed.
  • An exception could occur during execution of an except or else clause. Again, the exception is re-raised after the finally clause has been executed.
  • If the try statement reaches a break, continue or return statement, the finally clause will execute just prior to the break, continue or return statement’s execution.
  • If a finally clause includes a return statement, the returned value will be the one from the finally clause’s return statement, not the value from the try clause’s return statement.

Example 1:

def divide(x, y):
    try:
        result = x / y
    except ZeroDivisionError as e:
        print("division by zero!, Exception raised:",e)
    else:
        print("result is", result)
    finally:
        print("executing finally clause")
        
a = int(input("Enter value for X:"))
b = int(input("Enter value for Y:"))
divide(a, b)

Output:

>>>
Enter value for X:20
Enter value for Y:5
result is 4.0
executing finally clause

>>>
Enter value for X:10
Enter value for Y:0
division by zero!, Exception raised: division by zero
executing finally clause

Note: In the above example, the finally clause is executed in any event.


Example 2:

def divide(x, y):
    try:
        result = x / y
    except ZeroDivisionError as e:
        print("division by zero!, Exception raised:",e)
    else:
        print("result is", result)
    finally:
        print("executing finally clause")
divide(10, '4')

Output:

executing finally clause
Traceback (most recent call last):
File “C:\Users\Dawa Penjor\Desktop\test.py”, line 10, in
divide(10, ‘4’)
File “C:\Users\Dawa Penjor\Desktop\test.py”, line 3, in divide
result = x / y
TypeError: unsupported operand type(s) for /: ‘int’ and ‘str’

The TypeError raised by dividing two strings is not handled by the except clause and re-raised after the finally clause has been executed. In real-world applications, the finally clause is useful for releasing external resources (such as files or network connections), regardless of whether the use of the resource was successful.



Find us on YouTube: https://www.youtube.com/c/BhutanPythonCoder