Python-3.4.3/C4/Handling-Errors-and-Exceptions/English

From Script | Spoken-Tutorial
Jump to: navigation, search

Title of script: Handling errors and exceptions

Author: Arun KP

Keywords: Python, Ipython, error handling, exceptions, debugging, video tutorial


Visual Cue Narration
Show Slide title Welcome to the spoken tutorial on Handling errors and exceptions.
Show Slide

Objectives


In this tutorial, you will learn to,
  • Understand errors and exceptions
  • Handle errors and exceptions
Show Slide

System Specifications

To record this tutorial, I am using
  • Ubuntu Linux 16.04 operating system
  • Python 3.4.3
  • IPython 5.1.0
Show Slide

Prerequisite

To practise this tutorial, you should know how to
  • use functions and
  • carry-out testing and debugging

If not, see the relevant Python tutorials on this website.

Slide Errors In Python there are two kinds of errors:
  • syntax errorsand
  • exceptions
Show Slide

Syntax Error

Syntax errors are caused by incorrect usages and these are detected by parser.


For example:

if True print inside brackets inside double quotes done


It will give Syntax Error since colon is missing after True.

Show Slide

Exceptions


Exception is an error that occurs during execution of a program.


Python generates an exception that can be handled, which avoids the program to crash.


For example:

1/0


It will give ZeroDivisionError exception.

Open terminal Let us see these examples in action.


Open the terminal.

Type,

ipython3

Type ipython3 and press Enter.


From here onwards remember to press the Enter key after typing every command on the terminal.

Type,

if True print("done")


Highlight the arrow mark


Now type

if True print inside brackets inside double quotes done


The output shows SyntaxError.


It displays an ‘arrow’ pointing at the earliest point in the line where the error was detected.


In our case, the error is caused by missing colon after True in If clause

Type,

1 / 0

Now type,

1 / 0


Python throws an exception called ZeroDivisionError.


Even though the expression is syntactically correct, we cannot divide a number by zero.

Exception is a special kind of failure reported by the programming language.
Type,

a = input("Enter a number: ")

Enter ac

num = int(a)

Let's see how can we deal with Exceptions that occur in programs.


Type

a = input inside brackets inside double quotes Enter an integer


I will enter ac as input.


Now type, num is equal to int inside brackets a

Point to the error When you run this code, it throws a 'ValueError' Exception.


This is because, we are trying to convert the string to integer.

So now we can 'catch exceptions and write code to handle it.


For this we have try and except clause in Python.

[slide]

try..except..else


try:

statement1

statement2

Here is the syntax of try....except...else blocks.


First, the statements between the try and except keywords is executed.

except exception name:

exception handling statement(s)

If the statements do not cause any exception, the except clause is skipped.


If the statements cause any exception, then except clause is executed if exception name matches.

And the execution continues after the try statement.

else:

statement(s) when no exception


after statement(s)

The code in the else-block executes if the code in the try: block does not raise an exception.
Type,

a = input("Enter an integer: ")

ac

try:

num = int(a)

except ValueError:

print ("Wrong input")

Press Enter twice

output:

Wrong input

Type as shown.


Give ac as input.

Now we will type the try and except blocks.


Press Enter twice to get the output.


In the previous example,

We encountered a problem because we tried to convert the string ‘ac’ to integer.


Here conversion of string value to an integer is given inside try block.


ValueError exception is raised and so the output is displayed as Wrong input.

In the previous example, we found out what caused the error and then resolved to get a solution for it.


This whole process is called debugging.

Next we will see another case in try except statement with else clause.
b = input("Enter an integer: ")

23

try:

num = int(b)

except ValueError:

print ("Wrong input")

else:

print(“No exception “)

Press Enter twice


Highlight No exception

Lets change our previous code slightly.


Type as shown.


I will give input as 23.


Now type as shown.


This try… except statement has an optional else clause.


It is useful if the try clause does not raise an exception.

Open a text editor and type the following code.


def test():

prod = 1

for i in range(0, 10):

prod *= i / (i - 5)

print(prod)

Save it as file mymodule.py

Lets see another example for debugging.


Create a file mymodule.py with the following code.


The variable ‘i’ is iterated from 0 to 9.

Type,

from mymodule import test

test()


Let us run this code in Ipython.


Type,

from mymodule import test

test open and close brackets


Interpreter gives us ZeroDivisionError because there is a division by zero error.

Type,

%debug


Highlight the arrow mark


Highlight ipdb>

To find the value which caused the error, type


Percentage debug


The code which caused the error is shown by an arrow.


The prompt has changed to ipdb which is the ipython debugger mode.

[IPython Terminal]


ipdb> i

5

Using this debugger here, you can access variables in the previous code block.


We can check values of variables to inspect what went wrong.


For example, on typing ‘i’, we get 5 as output.


This means that the error was caused when the value of i became 5.


To exit from the ipdb prompt, press q and press Enter.

Show Slide

Summary

This brings us to the end of this tutorial. Let us summarize.


In this tutorial, we have learnt about

  • Errors and exceptions.
  • Handling exception using try and except.
  • Using percentage debug for debugging in ipython.
Show Slide

Self assessment questions

Here is a self assessment question for you to solve
  1. How do you start the debugger on ipython?
Show Slide

Solutions

And the answer,
  1. We start the debugger on ipython by saying, percentage debug
Show Slide Forum Please post your timed queries in this forum.
Show Slide Fossee Forum Please post your general queries on Python in this forum.
Slide Textbook Companion FOSSEE team coordinates the TBC project.
Show Slide

Acknowledgment


Spoken Tutorial Project is funded by NMEICT, MHRD, Govt. of India.

For more details, visit this website.

Previous slide This is Priya from IIT Bombay signing off.

Thank you.

Contributors and Content Editors

Nancyvarkey, Priyacst