You are on page 1of 30

Lecture 4

Python Exception Handling

1
What Is Error?
• The error is something that goes wrong in the
program, e.g., like a syntactical error.
• It occurs at compile time.
• An example of error:
if a<5
print(a)

if a<5
^
SyntaxError: invalid syntax

2
What Is Exception?
• The errors also occur at runtime, and we know
them as exceptions.
• They occur, for example, when a file we try to open
does not exist (FileNotFoundError), dividing a
number by zero (ZeroDivisionError), module we try
to import is not found (ImportError) etc.
• An exception disrupts the normal flow of the
program’s instructions.
• Whenever the interpreter has a problem it notifies
the user/programmer by raising an exception

3
Example of exceptions
ZeroDivisionError: division by any numeric zero
x = 2
y = 0
z = x / y
Error Message
Traceback (most recent call last):
File "test1.py", line 3, in <module>
z=x/y
ZeroDivisionError: division by zero

• Runtime error occur in the above code.


• A built-in exceptions in Python that are raised when
corresponding errors occur.
4
Python Built-in Exceptions
• Illegal operations can raise exceptions.

• The built-in exceptions can be generated by the


interpreter or built-in functions.

• Some of the common built-in exceptions in Python


programming along with the error that cause then
are tabulated in next slide.

5
Some of the common built-in exceptions
Exception Cause of Error
AssertionError Raised when assert statement fails.
AttributeError Raised when attribute assignment or reference fails.

EOFError Raised when the input() functions hits end-of-file condition.

FloatingPointError Raised when a floating point operation fails.

GeneratorExit Raise when a generator's close() method is called.

ImportError Raised when the imported module is not found.

IndexError Raised when index of a sequence is out of range.

KeyError Raised when a key is not found in a dictionary.

KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or delete).

MemoryError Raised when an operation runs out of memory.

NameError Raised when a variable is not found in local or global scope.

6
Some of the common built-in exceptions

Exception Cause of Error

SyntaxError Raised by parser when syntax error is encountered.

IndentationError Raised when there is incorrect indentation.

Raised when indentation consists of inconsistent tabs and


TabError spaces.

SystemError Raised when interpreter detects internal error.


SystemExit Raised by sys.exit() function.

Raised when a function gets argument of correct type but


ValueError
improper value.

Raised when second operand of division or modulo operation


ZeroDivisionError
is zero.

7
Example of exceptions
NameError: attempt to access an undeclared variable
>>> x
Traceback (innermost last):
File "<stdin>", line 1, in ?
NameError: name ‘x' is not defined

IndexError: request for an out-of-range index for sequence


>>> aList = []
>>> aList[0]
Traceback (innermost last):
File "<stdin>", line 1, in ?
IndexError: list index out of range

8
Example of exceptions
Cont’d
AttributeError: attempt to access an unknown object attribute
>>> class myClass(object):
... pass
...
>>> obj = myClass()
>>> obj.name = ‘Ali'
>>> obj.name
‘Ali'
>>> obj.address
Traceback (innermost last):
File "<stdin>", line 1, in ?
AttributeError: address

9
Handling exceptions
• By default, the interpreter handles exceptions by
stopping the program and printing an error
message

• However, we can override this behavior by catching


the exception

10
Example: nocatch.py
fin = open('bad_file')
for line in fin:
print (line)
fin.close()

Example: catch.py
try:
fin = open('bad_file')
for line in fin:
print (line)
fin.close()
except:
print ('Something went wrong.')

catching the exception


11
Detecting and Handling
Exceptions
• Exceptions can be detected by incorporating them
as part of a try statement.
• Any code suite of a try statement will be monitored
for exceptions.
• There are two main forms of the try statement:
 try-except
 try-finally

12
The try and except Block
• The try and except block in Python is used to catch and
handle exceptions.
• Python executes code following the try statement as a
“normal” part of the program.
• The code that follows the except statement is the
program’s response to any exceptions in the preceding
try clause.
• Following is the syntax of a Python try except  block.
try:
You do your operations here;
......................
except:
If there is an Exception, then execute this block.
13
The try and except Block
cont’d
• Following is the syntax of a Python try except block.

try:
You do your operations here;
......................
except:
If there is an Exception, then execute this block.

14
An example of (try and except)
def mult(x,y):
return (x*y)

try:
print(mult(3, a))
except:
print ("the function mult was not executed.")

The output:
the function mult was not executed.

Note: In the example above, python will throw an exception error.


This exception error will crash the program if it is unhandled.
The except clause determines how your program responds to
exceptions.
15
undeclared variable

An example of (try and except)


cont’d
def mult(x,y):
return (x*y)

try:
print(mult(3, a))
except:
print ("the function mult was not executed.")

You can include the try-except block inside the function as the following:
def mult(x,y):
try:
return (x * y)
except:
print ("the function mult was not executed.")

print(mult(3, a))

Question: the error that accrued with undeclared variable, can be


handled in this case? 16
Catching Specific Exceptions
• In the previous example, we did not mention any specific
exception in the except clause.

• This is not a good programming practice as it will catch all


exceptions and handle every case in the same way. We can
specify which exceptions an except clause will catch.

• A try clause can have any number of except clause to handle


them differently but only one will be executed in case an
exception occurs.

• We can use a built-in exception values to specify multiple


exceptions in an except clause. 
17
Example of catching specific exceptions
def div(x,y):
return (x/y)

a = 'n'
try:
print(div(3, a))
except ZeroDivisionError:
print("division by zero")
except (TypeError, NameError):
print(" There is an undeclared variable OR the data
type is not valid for this function")
except:# handle all other exceptions
print ('Something went wrong.')

Note: Catching Exception hides all errors, even those which are
completely unexpected.
This is why you should avoid bare except clauses in your Python
programs. Instead, you’ll want to refer to specific exception classes you
want to catch and handle. 18
The else Clause with “try and
except”
• In Python, using the else statement, you can
instruct a program to execute a certain block of
code only in the absence of exceptions

19
The else Clause with “try and except”

• Following is the syntax of a Python try except  block with else.

try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.

20
Example of else Clause with “try and except”

def div(x,y):
return (x/y)

try:
print(div(3, 4))
except ZeroDivisionError:
print("division by zero")
else:
print("the div function is executed")

The output:
0.75
the div function is executed
21
Try-Finally Statement
• The try statement in Python can have an optional
finally statement.
• This statement is executed no matter what, and is
generally used to release external resources.
• The syntax of the try-finally is placed below:

try:
You do your operations here;
......................
You can do any exception, this may be skipped.
finally:
This would always be executed.
......................

22
Example: Try-Finally Statement
Here is an example of file operations to illustrate this

try:
fh = open("testfile", "w")
fh.write("This is my test file")
finally:
fh.close()

This type of construct makes sure the file is closed even if an


exception occurs.

23
Cleaning Up After
Using finally
• Imagine that you always had to implement some sort of
action to clean up after executing your code. Python enables
you to do so using the finally statement.

24
Example: handling exception with Try-
Finally Statement
• "finally" and "except" can be used together for the same
try block
• Here is an example of file operations to illustrate this
try:
fob = open('test', 'r')
fob.write("It's my test file ")
print ('try block executed')
except IOError:
print("Error: can't find file or read data")
finally:
fob.close()
print ('Close the file')

In this case, the file is closed even if an exception occurs!!!!!


This code can be enhanced … (see the next slide)
25
Example: handling exception with Try-
Finally Statement Cont’d

try:
fob = open('test', 'r')
try:
fob.write("It's my test file")
print ('try block executed')
finally:
fob.close()
print ('finally block executed to close the file')
except IOError:
print ("Error: can't find file or read data")

Can be enhanced?
Try to use “else”

26
Python Date and Time
• There are various ways Python supplies date and
time feature to add to the program. Python's Time
and calendar module help in tracking date and
time. Also, the 'DateTime' provides classes for
controlling date and time in both simple and
complex ways.

27
Example

28
Example Current Time

29
Example Calendar Of A Month

30

You might also like