0% found this document useful (0 votes)
5 views16 pages

Unit 5 CS PT 4

The document discusses exceptions and exception propagation in Python, highlighting the difference between syntax errors and runtime exceptions. It explains built-in exceptions, user-defined exceptions, and the concept of exception handling using try, except, else, and finally blocks. Additionally, it provides examples of various exceptions and demonstrates how to create custom exceptions.

Uploaded by

Shreeya Rao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views16 pages

Unit 5 CS PT 4

The document discusses exceptions and exception propagation in Python, highlighting the difference between syntax errors and runtime exceptions. It explains built-in exceptions, user-defined exceptions, and the concept of exception handling using try, except, else, and finally blocks. Additionally, it provides examples of various exceptions and demonstrates how to create custom exceptions.

Uploaded by

Shreeya Rao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Unit V: Exceptions,Exception Propagation 2020

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.

1 Department of Computer Science &Engg, PESU


Unit V: Exceptions,Exception Propagation 2020

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.

Example 2: division by zero error

Python3 defines 63 built-in exceptions.The below figure shows a small view of the Exception tree.

2 Department of Computer Science &Engg, PESU


Unit V: Exceptions,Exception Propagation 2020

The Exceptions fall into 2 categories namely

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

Keyboard Interrupt Raised when users hit Ctrl-C,the interrupt key


Overflow Error Raised when a floating-point expression
evaluates to a value that is too large
ZeroDivision Error Raised when attempting to divide by 0
IO Error Raised when an I/O operation fails for an I/O

3 Department of Computer Science &Engg, PESU


Unit V: Exceptions,Exception Propagation 2020

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

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ZeroDivisionError: division by zero

Example 4:
>>>lst=[1,4,5]

>>>lst[3]

Output

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

4 Department of Computer Science &Engg, PESU


Unit V: Exceptions,Exception Propagation 2020

IndexError: list index out of range

Example 5:
>>> a+10

Output

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name 'a' is not defined

Example 6:

>>> '2'*'6'

Output

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: can't multiply sequence by non-int of type 'str'

Example 7:

>>>int('3.5')

Output

5 Department of Computer Science &Engg, PESU


Unit V: Exceptions,Exception Propagation 2020

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ValueError: invalid literal for int() with base 10: '3.5'

Example 8:

>>> 2.0**10000000

Output:

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

OverflowError: (34, 'Result too large')

User defined exception


It is not possible for a language to specify all possible unusual cases. So the users can also specify
exception as a class which inherits from a class called exception.
When an exception is occurred , the program is terminated. Can we avoid this termination?Can
we get a chance to proceed further? Can we have graceful degradation?Yes and this concept is
called exception handling.
A few components and terminologies used with exception handling:
a) try:
The try block lets you test a block of code for errorsindicating to the Python runtime that
something unusual could happen in the suite of code.

b) except [<type>]:

6 Department of Computer Science &Engg, PESU


Unit V: Exceptions,Exception Propagation 2020

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:

7 Department of Computer Science &Engg, PESU


Unit V: Exceptions,Exception Propagation 2020

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

8 Department of Computer Science &Engg, PESU


Unit V: Exceptions,Exception Propagation 2020

try:
Foo(0)
except ArithmeticError:
print("An error occurred")
print("terminate")
Output:
An error occurred
terminate

d) Matching of except blocks:


The raised or thrown exception object is matched with the except blocks in the order in which
they occur in the try-except statement. The code following the first match is executed. It is always
the first match and not the best match. If no match occurs and there is an default except block
(with no exception specifed), then that block will be executed.
Example 13:
The try block will generate a NameError, because x is not defined:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Output
Variable x is not defined

Example 14:
m = 10
#n = 2

9 Department of Computer Science &Engg, PESU


Unit V: Exceptions,Exception Propagation 2020

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")

Output 1:When n=0


one
all other exceptions : division by zero

Output 2:When n=2


one
res : 5.0
two
no such name : name 'myvar' is not defined

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.

10 Department of Computer Science &Engg, PESU


Unit V: Exceptions,Exception Propagation 2020

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

11 Department of Computer Science &Engg, PESU


Unit V: Exceptions,Exception Propagation 2020

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.

If an exception is raised inside a function, it can be handled in two ways

• Inside the function


• Outside the function

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

12 Department of Computer Science &Engg, PESU


Unit V: Exceptions,Exception Propagation 2020

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("An exception is raised")

print("Exception Programming")

Output:When x=0

An exception is raised

Exception Programming

Output:When x=10

Exception Programming

13 Department of Computer Science &Engg, PESU


Unit V: Exceptions,Exception Propagation 2020

User defined exceptions

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")

14 Department of Computer Science &Engg, PESU


Unit V: Exceptions,Exception Propagation 2020

Output:When 1<=n<=100
enter a number:5
number is fne : 5
thats all
Output:When n>=100
enter a number:105

number not in range

thats all

15 Department of Computer Science &Engg, PESU


Unit V: Exceptions,Exception Propagation 2020

16 Department of Computer Science &Engg, PESU

You might also like