Unit 5 CS PT 4
Unit 5 CS PT 4
Introduction
We usually try to write programs that do not produce errors, but the unfortunate truth is that
even programs written by the experienced developers sometimes crash. And even if a program is
perfect, it could still produce errors because the data coming from outside the program is
malformed and causes errors in the program. This is a big problem with server programs, such as
web, mail and gaming servers. Hence it is good to study about errors that can occur before and
during program execution.
Two basic types of errors can occur when running a python program. They are
1. Syntax Errors
2. Exceptions
Syntax Errors
Syntax errors or parsing errors are errors that are due to incorrect format of a python statement.
These errors occur while the statement or program is being translated to machine language and
before it is being executed. A component of python’s interpreter called as parser discover these
errors.
Example 1:
In the above snapshot we can observe that the error is due to an incorrect syntax(format) of a
python statement. These errors occur before the execution of a statement.
Exceptions
Now let’s focus on errors that occur during the execution of a statement or a program. They do
not occur because of malformed python statement or program but rather because of the
program in the erroneous state. When an error is detected during execution, it is called an
exception. Let’s consider some example where the statements or program is syntactically correct
but still causes an error.
Python3 defines 63 built-in exceptions.The below figure shows a small view of the Exception tree.
1. Built-In exceptions
2. User defined exceptions
Built-In exceptions
There are a number of exceptions which Python knows. We call them built-in exceptions. The
table below lists few of the built-in exceptions.
Exceptions Explanation
related reason
Index Error Raised when a sequence index is outside the
range of valid indexes
Name Error Raised when attempting to evaluate an
unassigned identifier
Type Error Raised when an operation or function is
applied to an object of the wrong type
Value Error Raised when an operation or function has an
argument of the right type but incorrect value
Example 3:
>>> 6/0
Output
Example 4:
>>>lst=[1,4,5]
>>>lst[3]
Output
Example 5:
>>> a+10
Output
Example 6:
>>> '2'*'6'
Output
Example 7:
>>>int('3.5')
Output
Example 8:
>>> 2.0**10000000
Output:
b) except [<type>]:
We should have at least one except block to which the control shall be transferred if and only if
something unusual happens in the try suite.Let us say you walk home or tohostel every day from
the college. That is normal. Some day, you get drenched in rain. Some other day, you trip and
your footware breaks down. Do you treat these unusual cases the same way? Similarly, within
the try suite, there could be any one of the number of exceptional cases happening – each of
which might require diferent ways of handling.
So try block may be followed by one or more except block – all but one of them specifying the
name of the exception – one of them may provide a common and default way of handling all
exceptions.
Example 9:
try:
print(x)
except:
print("An exception occurred as x is not defined ")
Output
An exception occurredas x is not defined
Example 10:
try:
y=1/0
except ZeroDivisionError:
print("Python exception raised")
Output:
Python exception raised
You can use the else keyword to define a block of code to be executed if no errors were raised:
In he below example ,the try block does not raise any errors, so the else block is executed:
Example 11:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Output
Hello
Nothing went wrong
c) Raising exception:
We indicate something is unusual or python runtime itself will indicate something exceptional
using raise statement.
Syntax
raise Exception1name(<message>)
This causes creation of an exception object with the message. The object also remembers the
place in the code (line number, function name, how this function got called on). The raising of
exception causes the program to abort if not in a try block or transfer the control to the end of try
block to match the except blocks.
Example 12:
def Foo(number):
raise ZeroDivisionError
try:
Foo(0)
except ArithmeticError:
print("An error occurred")
print("terminate")
Output:
An error occurred
terminate
Example 14:
m = 10
#n = 2
n=0
try:
print("one")
print("res : ", m / n)
print("two")
print(myvar)
print("three")
except NameError as e:
print("no such name : ", e)
except Exception as e:
print("all other exceptions : ", e)
except:
print("all exceptions")
e) Finally block:
This is an optional block which follows all the except blocks. It is part of the try statement. This
block shall be executed on both normal flow and exceptional flow.
Let us understand the flow of execution.
i) Normal flow
try block – fnally block if any – code following try block
ii) Exceptional flow
try block – exit the try block on an exception – fnd the frst matching except block –
execute the matched except block – fnally block – code following try block
Observe there is no mechanism in any language including Python to go back to the try
block – no way to resume at the point of exception.
Example 15:
def division(n):
try:
n=1/n
except ZeroDivisionError:
print("Division failed")
n = None
else:
print("code is correct")
finally:
print("finally is executed")
return n
print(division(4))
print(division(0))
Output:
code is correct
finally is executed
0.25
Division failed
finally is executed
None
f)Exception propagation:
We say that a try block has dynamic scope. Any exception raised in the block or any function
called from there are considered part of the try block. Any exception raised within these
functions called from there will cause the control to be propagated backwards to the except
blocks of this try block.
Let’s consider the first case i.e handling of exception inside the function through an example
Example 16:
def mathOp(n):
try:
return 1 / n
except ArithmeticError:
print("Division not possible")
return None
#mathOp(0)
mathOp(10)
print("successfully completed")
Output:When n=0
Division not possible
successfully completed
Output:When n=10
successfully completed
The ZeroDivisionError exception is raised inside the mathOp() function, and it doesn't leave the
function - the function itself takes care of it.
Let’s consider the second case i.e handling of exception outside the function through an example
Example 17:
def mathOp(x):
return 1 / x
try:
mathOp(0)
except ArithmeticError:
print("Exception Programming")
Output:When x=0
An exception is raised
Exception Programming
Output:When x=10
Exception Programming
Now let us understand how to create our own exceptions(User defined exceptions)
In Python, users can define custom exceptions by creating a new class. This exception class has to
be derived, either directly or indirectly, from the built-in Exception class. Most of the built-in
exceptions are also derived from this class.
Here, we have created a user-defined exception called MyException which inherits from
the Exception class. This new exception, like other exceptions, can be raised using
the raise statement with an optional error message.
Example 18:
class MyException(Exception):
def __init__(self, str):
self.str = str
def __str__(self):
return self.str
# check whether n is between 1 and 100
n = int(input("enter a number:"))
try:
if not 1 <= n <= 100 :
raise MyException("number not in range")
print("number is fine : ", n)
except MyException as e:
print(e)
print("thats all")
Output:When 1<=n<=100
enter a number:5
number is fne : 5
thats all
Output:When n>=100
enter a number:105
thats all