Wednesday, January 1, 2020

Python tutorial 16 | Exception handling part 2 | Try except statement

Moving on with Python Tutorials for Beginners, let us go to the next one from Exception Handling part 1 tutorial. This Python beginner tutorial further explains how to handle any exception in Python. Please view the Python video tutorial 16 or read on... I have explained what are exceptions in my previous Python tutorial 15. In Python programming, the Python try statement syntax can also have an optional else clause:

try:
    try clause
except named_exception(s):
    except clause

else:
    else clause

In the above try statement format, we can put code in the else clause that will only be run when no exception is thrown in the try clause. In other words, the else clause should have code to be be run after the successful completion of the try clause. The else clause may be written after multiple excepts also. Now, let us see the else clause Python examples.

# Python code example
# This Python code, as is, should run the else clause.
try:
    i = 10 # if you comment this line, it should generate an exception and skip the else clause
    print (i*2)
except NameError:
    print ('Please define the variable first.')
else:
    print ('Printed the double of the value!')

The Python try statement syntax can also have an optional finally clause:
try:
    try clause
except named_exception(s):
    except clause

else:
    else clause
finally:
    finally clause

In the above try statement format, we can put code in the finally clause that will always be run whether an exception is thrown in the try clause or not. The finally clause is used to run "clean up" or "tear down" actions like release file handles, close any database connections or remove any temporary files. The finally clause may be written after multiple excepts also. Now, let us see the finally clause Python example.

# Python code example
# This Python code should always run the finally clause.
try:
    # Input a zero to get an exception, non-zero otherwise
    i = input ('Enter an integer to divide 10 by:')
    i = int (i)
    print (10 / i)
except :
    print ('There was a problem.')
else:
    print ('Printed the quotient value!')
finally:
    print ('The finally message is always printed.')

In Python programming, there is the raise statement with the following syntax:
raise named_exception (error_message)

In the above raise statement format, raise is followed by the exception name. The raise statement in Python throws the named exception along with the given error message.

# Python code examples
raise ValueError ('Invalid number!')
# Comment the previous line and uncomment the following line to raise an exception
# raise TypeError ('That is an incorrect type.')

Want to see exception handling working with more Python samples e.g. file handling? View my Python video tutorial 16. Thank you.

No comments:

Post a Comment