December 22, 2019

Python tutorial 15 | Exception handling part 1 | Try except statement

Let us go to an important tutorial in the Python Tutorials for Beginners. This Python beginner tutorial explains exceptions in Python and how to handle them. First, what are exceptions? Exceptions are the errors that are thrown during script execution. Exceptions are different from syntax errors, which are thrown before script execution. If we do not handle an exception, our script execution stops with an error message. Let us see some Python exception examples.

# Python code
print (i * 2)   # throws NameError exception because variable 'i' is not defined
int ('Hi')   # throws ValueError exception because 'Hi' is an invalid argument to the int function
print (1 / 0)   # throws ZeroDivisionError because division by zero is not allowed in Python programming

We can handle exceptions in Python using the Python try except statement. This means that we can protect our Python script from stopping abruptly. The Python try statement syntax is:
try:
    try clause
except named exception:
    except clause

In the above try statement format, the try clause is a code block with one or more statements in it. Same for the except clause. When Python runs the try clause, there are three possibilities 1), 2a) or 2b):
1) If there is no exception, the try clause is completed and the except clause is skipped.
2) If an exception is thrown in the try clause, the remaining statements in the try clause are skipped. Python matches the thrown exception with the named exception(s) after except:
2a) If the exception matches, the except clause  is run.
2b) If the exception does not match, the Python script execution stops with an error message.

Now, let us see the Python try except statement example.

# Python code example
try:
    i = 10 # comment this line to generate an exception
    print (i*2)
except NameError:
    print ('Please define the variable first.')

The Python try statement syntax can also have multiple excepts:
try:
    try clause
except named exception 1:
    except clause 1
except named exception 2:
    except clause 2
.
.
.
except named exception n:
    except clause n

In the above try statement format, there are multiple except clauses within the try statement. When Python runs the try clause there are three possibilities 1), 2a) or 2b):
1) If there is no exception, the try clause is completed and all the except clauses are skipped.
2) If an exception thrown in the try clause, the remaining statements in the try clause are skipped. Python matches the thrown exception with the named exception(s) after each except:
2a) If the exception matches any named exception, only that except clause  is run (and all the other except clauses are skipped).
2b) If the exception does not match any named exception in any except, the Python script execution stops with an error message. In order to catch any unnamed exception, we can have the last except without any named exceptions (as in the Python code examples below).


# Python code example
try:
    i = 1 # comment this line to generate the NameError exception
    # print (int('some string')) # uncomment this line to generate the ValueError exception
    print (i*10)
    # print  (i / 0) # uncomment this line to generate an unnamed exception
except NameError:
    print ('Please define the variable first.')
except ValueError:
   print ('Please provide a valid argument to the int function')
except:
    print ('There was a problem.')

1 comment:

  1. Very useful and informative blog. Thank you so much for these kinds of informative blogs.
    AngularJS Training in Pune

    ReplyDelete

Note: Only a member of this blog may post a comment.