0% found this document useful (0 votes)
3 views10 pages

Chapter 1 Exception Handling in Python Notes

Chapter 1 discusses exception handling in Python, outlining various types of errors such as syntax errors, runtime errors, and logical errors. It explains built-in exceptions, user-defined exceptions, and the process of raising and handling exceptions using try, except, else, and finally clauses. The chapter emphasizes the importance of exception handling in maintaining program stability and provides examples of how to implement it effectively.

Uploaded by

phoenixchess7
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)
3 views10 pages

Chapter 1 Exception Handling in Python Notes

Chapter 1 discusses exception handling in Python, outlining various types of errors such as syntax errors, runtime errors, and logical errors. It explains built-in exceptions, user-defined exceptions, and the process of raising and handling exceptions using try, except, else, and finally clauses. The chapter emphasizes the importance of exception handling in maintaining program stability and provides examples of how to implement it effectively.

Uploaded by

phoenixchess7
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

CHAPTER 1 EXCEPTION HANDLING IN PYTHON

INTRODUCTION
The program does not execute at all or the program executes but generates
unexpected output or behaves abnormally.
These occur when there are
 Syntax errors(Compile time error, semantic error)
 Runtime errors
 Logical errors , in the code.

Syntax Error
 Syntax errors are detected when we have not followed the rules of the
particular programming language while writing a program.
 These errors are also known as parsing errors.
 On encountering a syntax error, the interpreter does not execute the
program unless we rectify the errors, save and rerun the program.
EX: def test():
marks=20
if marks>10:
print ”Good Score”
 The above example , syntax error is rasied due to missing of parentheses

Exceptions
An exception is a Python object that represents an error, When an error occurs
during the execution of a program, is called exception.

BUILT IN EXCEPTIONS
commonly occurring exceptions are usually defined in the compiler/interpreter,
these are called built-in [Link] are mainly 12 types
1. SyntaxError
It is raised when there is an error in the syntax of the Python code
Ex: def test():
marks=20
if marks>10:
print ”Good Score”
output: ‘Syntax error’ parentheses missing in the print statement

2. ValueError
It is raised when a built-in method or operation receives an argument that has
the right data type but mismatched or inappropriate values.
Ex: a=’hello’
int(a)
output: ‘Value error’ mismatched data types for assigned string value for a
variable ‘a’

3. IO Error
It is raised when the file specified in a program statement cannot be opened.
Ex: try:
f=open(“[Link]”,’r’)
print([Link]())
[Link]
except IOError
print(‘file not found’)

4. KeyboardInterrupt
It is raised when the user accidentally hits the Delete or Esc key
while executing a program due to which the normal flow of the
program is interrupted.

5. ImportError
It is raised when the requested module definition is not found.
Ex: from math import cube
Output: import error
6. EOFError
It is raised when the end of file condition is reached without
reading any data by input().
Ex: try:
While True:
line=input(“enter some text:”)
print(“you entered:”,line)
except EOFError:
print(“end of input reached”)

7. ZeroDivisionError
It is raised when the denominator in a division operation is
zero.
Ex: a=10
b=0
c=a/b
print(“value of c:”,c)

8. IndexError
It is raised when the index or subscript in a sequence is out of range.
Ex: a=[1,2,3,4]
Print(a[10])

9. NameError
It is raised when a local or global variable name is not defined.
Ex: a=12
b=20
print(a,b,c)

10. IndentationError
It is raised due to incorrect indentation in the program code.
Ex: a=10
b=20
if(a>b):
print(“a is big”)
else:
print(“b is big”)

11. TypeError
It is raised when an operator is supplied with a value of incorrect data type .
Ex: x=10
y=’ram’
c=x+y
print(“value of c”,c)

12. Overflow Error


It is raised when the result of a calculation exceeds the maximum limit
for numeric data type.
Ex: n=999.999
for i in range(1,100):
n=n**10

User defined exception-


A programmer can also create exception to suit ones requirements, these are
called user defined exceptions.

Raising Exception / raise statement

 Each time an error is detected in a program, the Python interpreter raises


(throws) an exception.
 Exception andlers are designed to execute when a specific exception is
raised.
 Programmers can also forcefully raise exceptions in a program using the
raise and assert statements.
 Once an exception is raised, no further statement in the current block of
code is executed.
 The raise statement can be used to throw an exception.
 syntax of raise statement is:
raise exception-name[(optional argument)]

Ex: numbers= [40,50,60,70,80]


length=10
if length>len(numbers):
raise IndexError
print(“no execution”)
else:
print(length)

( From above example, the value of variable length is greater than the
length of the list numbers, an IndexError exception will be raised. The
statement following the raise statement will not be executed. So the
message “NO EXECUTION” will not be displayed in this case.)
Assert Statement
 An assert statement in Python is used to test an expression in the program
code.
 If the result after testing comes false, then the exception is raised.
 Syntax for assert statement is:
assert Expression[,arguments]
 On encountering an assert statement, Python evaluates the expression
given immediately after the assert keyword.
 If this expression is false, an Assertion Error exception is raised which
can be handled like any other exception

Ex: print("use of assert statement")


def negativecheck(number):
assert(number>=0), "OOPS... Negative Number"
print(number*number)
print (negativecheck(100))
print (negativecheck(-350))

Handling Exception
 Writing additional code in a program to give proper messages or
instructions to the user on encountering an exception. This process is
known as Exception Handling

Need for Exception Handling


 Exception handling is being used not only in Python programming but in
most programming languages like C++, Java, Ruby, etc.
 It is a useful technique that helps in capturing runtime errors and handling
them so as to avoid the program getting crashed.
 Python categorises exceptions into distinct types so that specific
exception handlers , can be created for each type.
 Exception handlers separate the main logic of the program from the error
detection and correction code. The segment of code where there is any
possibility of error or exception, is placed inside one block. The code to
be executed in case the exception has occurred, is placed inside another
block. These statements for detection and reporting the exception do not
affect the main logic of the program.
 The compiler or interpreter keeps track of the exact position where the
error has occurred.
 Exception handling can be done for both user-defined
and built-in exceptions
Process of Handling Exception

 When an error occurs, Python interpreter creates an object called the


exception object.
 This object contains information about the error like its type, file name
and position in the program where the error has occurred.
 The object is handed over to the runtime system so that it can find an
appropriate code to handle this particular exception.
 This process of creating an exception object and handing it over to the
runtime system is called throwing an exception.
 when an exception occurs while executing a particular program statement
the control jumps to an exception handler, abandoning execution of the
remaining program statements.
 The runtime system searches the entire program for a block of code,
called the exception handler that can handle the raised exception.
 The runtime system first searches for the method in which the error has
occurred and the exception has been raised. If not found, then it searches
the method from which this method was called.
 This hierarchical search in reverse order continues till the exception
handler is found. This entire list of methods is known as call stack.
 When a suitable handler is found in the call stack, it is executed by the
runtime process.
 This process of executing a suitable handler is known as catching the
exception.
 If the runtime system is not able to find an appropriate exception after
searching all the methods in the call stack, then the program execution
stops.

Catching Exceptions
 An exception is said to be caught when a code that is designed to handle a
particular exception is executed.
 Exceptions, if any, are caught in the try block and handle in except block.
 While executing the program, if an exception is encountered, further
execution of the code inside the try block is stopped and the control is
transferred to the except block
 Every try block is followed by an except block. The appropriate code to
handle each of the possible exceptions are written inside the except
clause.
 Syntax:
try:
[ program statements where exceptions might occur]
except [exception-name]:
[ code for exception handling if the exception-name error is
encountered]
Ex: print ("Practicing for try block")
try:
numerator=50
denom=int(input("Enter the denominator"))
quotient=(numerator/denom)
print(quotient)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO.... not allowed")
print(“OUTSIDE try..except block”)

Use of multiple except clauses (Reffer text book for explnation)

print ("Handling multiple exceptions")


try:
numerator=50
denom=int(input("Enter the denominator: "))
print (numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
except ValueError:
print ("Only INTEGERS should be entered")

Use of except without specifying an exception


print ("Handling exceptions without naming them")
try:
numerator=50
denom=int(input("Enter the denominator"))
quotient=(numerator/denom)
print ("Division performed successfully")
except ValueError:
print ("Only INTEGERS should be entered")
except:
print(" OOPS.....SOME EXCEPTION RAISED")
Try….except..else..clause
Use of else clause
print ("Handling exception using try...except...else")
try:
numerator=50
denom=int(input("Enter the denominator: "))
quotient=(numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
except ValueError:
print ("Only INTEGERS should be entered")
else:
print ("The result of division operation is ", quotient)

Finally Clause
 The try statement in Python can also have an optional finally clause.
 The statements inside the finally block are always executed regardless of
whether an exception has occurred in the try block or not.

Use of finally clause


Ex:
print ("Handling exception using try...except...else...finally")
try:
numerator=50
denom=int(input("Enter the denominator: "))
quotient=(numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
except ValueError:
print ("Only INTEGERS should be entered")
else:
print ("The result of division operation is ", quotient)
finally:
print ("OVER AND OUT")
Recovering through finally clause
If an error has been detected in the try block and the exception has been
thrown, the appropriate except block will be executed to handle the error.
But if the exception is not handled by any of the except clauses, then it is
re-raised after the execution of the finally block

Ex:
print (" Practicing for try block")
try:
numerator=50
denom=int(input("Enter the denominator"))
quotient=(numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
else:
print ("The result of division operation is ", quotient)
finally:
print ("OVER AND OUT")

You might also like