Lecture 4
Lecture 4
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
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.
KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or delete).
6
Some of the common built-in exceptions
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
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
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.')
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.
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))
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”
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()
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')
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