0% found this document useful (0 votes)
7 views9 pages

Python Compile and Runtime Errors Guide

Chapter 8 covers exception handling in Python, explaining compile-time errors and run-time errors (exceptions). It details built-in exceptions, how to handle exceptions using try, except, and finally clauses, and provides examples of user-defined exceptions. The chapter emphasizes the importance of managing exceptions to ensure program stability and correct output.

Uploaded by

bbawa631
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)
7 views9 pages

Python Compile and Runtime Errors Guide

Chapter 8 covers exception handling in Python, explaining compile-time errors and run-time errors (exceptions). It details built-in exceptions, how to handle exceptions using try, except, and finally clauses, and provides examples of user-defined exceptions. The chapter emphasizes the importance of managing exceptions to ensure program stability and correct output.

Uploaded by

bbawa631
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 8: Exception Handling

While writing a Python code, certain errors may occur. In the first
place, these errors can prevent the program from being executed by
the interpreter. These errors are called compile time errorS. For an
instance, forgetting to follow exact syntax of a particular construct
such as if statement or making a spelling mistake, missing a
semicolon or colon, may cause interpreter/compile time error. The
program gets executed only after these errors are rectified. Let us
consider a program given in Code 8.1. This program determines
whether a number is even. In the if statement, we see that colon (:) is
missing. The execution of this code raises a syntax error as presented
in Fig. 8.1.
Code: 8.1. Illustration of interpreter time error (syntax error).
#This program illustrates syntax error

number=input('Enter a number:)
number=int(number)
if number%2==0
print('Number is even')
print('out of if block')

CAWindowsisystem32cnd eje
progs yt hon corpi le [Link]
"conpile orror. py". line
if runbe rt20
yntexError: invalid syntax
DEpyPros?
Fig. 8.1. Output of Code 8.1

8.1. Exception
There exists some errors which occur at run time in the program. For
instance, attempting to divide by zero or accessing a list, which is not
defined, opening a file that does not exist are common examples of
run time errors. The run time error is called exception. By the
occurrence of theseerrors, Python creates an exception object. If not
handled properly, itprints a traceback to that error along with some
details about why that error has occurred. For instance, consider a

207
Programming in Python

simple code given in Code: 8.2. We see that there is no syrntax erro
in this code, therefore, it executes without any error. The
this code is given in Fig. 8.2., we see if the user inputs the output
value
of
number as 0then the expression c=15/number evaluates to c=15 of
then due to division by zero, ZeroDivisionError exception 0ccurs
we don't obtain the output. and

Code: 8.2. Illustration of runtime error (Exception).


# This program illustrates run time error

number=input('Enter a number:')
number=int(number)
c=15/number
print(c)

CAWindows system 32cmd exe


D:pyprogs >pyt hon runt ine error. py
Entes a nunber :8
recent call last >:
L d e e [Link]. 1ine . in Knodu le>
e-15/nsnher
Zerobiv ie ioarroP: divis ion by zero
D:SPypro2
Fig. 8.2. Output of Code 8.2

8.2. Python Built-in Exceptions


Python language detects exceptions if they occur during the executo
of a program. There exists numerous built-inPython exceptions liste
in Table 8.1. with the description of each.
Exception Cause
AssertionError Raised when assert statement fails. reference
AttributeError Raised when attribute assignment or
fails. end-of-file

EOFError Raised when the input() functions hits


condition.

208
Chapter 8: Exception Handling

FloatingPointError Raised when a floating point operation fails.


GeneratorExit Raise when a generator's close(0 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.
Keyboardlnterrupt Raised when the user hits interrupt key (Ctrltc or
delete).
MemoryError Raised when an operation runs out of memory.
NameError Raised when a variable is not found in local or
global scope.
NotImplementedError Raised by abstract methods.
OSError Raised when system operation causes system
related error.
OverfloWError Raised when result of an arithmetic operation is
too largeto be represented.
ReferenceError Raised when a weak reference proxy is used to
access a garbage collected referent.
RuntimeError Raised when an error does not fall under any
other category.
StopIteration Raised by next) function to indicate that there is
no further item to be returned by iterator.
SyntaxError Raised by parser when syntax error is
encountered.
IndentationError Raised when there is incorrect indentation.
TabError Raised when indentation consists of inconsistent
tabs and spaces.
SystemError Raised when interpreter detects internal error.
SystemExit Raised by [Link]() function.
TypeError Raised when a function or operation is applied to
an object of incorrect type.
UnboundLocalError Raised when a reference is made to a local
variable in a function or method, but no value has
been bound to that variable.
UnicodeError Raised when a Unicode-related encoding or
decoding error occurs.
UnicodeEncodeError Raised when a Unicode-related error occurs
during encoding.
UnicodeDecodeError Raised when a Unicode-related error occurs
during decoding.

209
Programming in Python

UnicodeTranslateError Raised when a Unicode-related error


during translating. oCcurs
ValueError Raised when a function gets argument
of
type but improper value. correct
ZeroDivisionError Rajsed when second operand of division or
modulo operation is zero.
Table 8.1. Python Built-in Exceptions

8.3. Exception Handling


When an exception occurs, the current process stops and
calling process until it is handled to obtain the result. If not passes it to the
the program crashes and the intended output is not obtained handled
and the propetly,
comes to a halt. nroorm

8.3.1. Try, Except, and Finally


In Java, try and catch blocks are used to
exceptions can be handled using a tryhandle and
exceptions, in Python,
except statements. A
critical operation which can raise
the try clause and the code for exception is included in
in except clause. Consider a handling the exception is included
programming example in Code: 8.3. In
this program, we see that the user is asked to input an integer number
and then its reciprocal will be
user enters a character or float computed. In the output, we see that
(real) value then ValueError exception
occurs, which is caught by the except clause
and the
message "please try again" along with exception is appropriate eror
user. The while loop executes until the displayed to tie
value as an input for the computation of user supplies a valid integ
portion that valid reciprocal. The riuva
can cause exception is placed inside
18 no exception then programs executes the try block. lr
Occurs then it is caught by the exceptwithclause.
normalTherefore,
flow and ifweeriv
see
exception occurs three times for inputting a, 1.5, and 0and handled
by the except block of the program by providing value error and
divide by zero
to fetch the typeerror
of
messages. In the code exc info module is used
module is necessary toexception from the Sys module. There fore, sys
import in this program.
Chapter 8: Exception Handling

Code: 8.3. Illustration of Try and Except clauses.


# This program illustrates to handle exceptions using try and except
clauses

import sys
while True:
try:
X= int(input("Enter an integer: ")
r=1/x
break
except:
print("Oops!",sys.exc_info()[0],"occured.")
print("Please try again.")
print)
rint("The reciprocal of"x, "is",r)

Output
Enter an integer:a
Oops! <class "ValueError>occured.
Please try again.
Enter an integer:1.5
Oops! <class "ValueError>occured.
Please try again.
Enter an integer:0
Oops! <class 'ZeroDivisionError>occured.
Please try again.

Enter an integer:5
The reciprocal of 5 is 0.2

211
Programming in Python

8.3.2. Catching Specific Exceptions in Python


We can also handle exceptions separately rather than all
in one block. In Python, atry clause can have multiple exceptexceptions
just like atry block can have multiple catch blocks in Java. clauses
of them will be executed depending upon the type of Only one
exception. The code for the same is illustrated in Code 8.4 occutted
Code: 8.4. Illustration of multiple except clauses.
try:
# do something
pass

except Value Error:


#handle ValueError exception
pass

except (TypeError, ZeroDivisionError):


# bandle multiple exceptions
#TypeErrOr and ZeroDivisionError
pass

except:
# handle all other exceptions
pass

8.3.3. try..finally
As we have seen that the try statement can have multiple excep!
statements. Alike Java, Python also exhibit an optional clause
'finally'. It gets executed automatically, and is mostly usedto release
external resources. For example, while developing some large
projects, we may be connected to a server on the network orto a tile
of GUI. Then in such situations, to release all the resources finally
exception clause can be used. It will ensurethat all resources are treed
up to guarantee successful execution of the program

program. The
illustrating the same is displayed in Code 8.5.
Chapter &: Exception Handling

Code: 8.5. Illustration of finally clause.


try:
fp = open("[Link]",encoding ='utf-8')
#perform file operations
finally:
[Link]()

Note: This type of construct makes sure the file is closed even if an
exception occurs.

8.4. Python User-Defined Exceptions


In Python, users can create their own exceptions. This can be done by
creating a new class which is derived from the Exception class. It is
to be noted that most of the built in exceptions are also derived from
the Exception class. On the Python prompt, a user defined exception
can be created as follows as shown in Code 8.6. We see that a user
iefined exception NewException is created which is derived from the
Exception class. This NewException can be raised just like other
existing exceptions by using the raise statement with an optional error
message.

Code: 8.6. Illustration of user defined exception NewException.


>>> class NewException(Exception):
pass

>>> raise NewException


Traceback (most recent call last):

main NewException

>>> raise NewException("An error has occurred")


Traceback (most recent call last):

main NewException:An error has occurred

213
Programming in Python

An illustration of user defined exception is given in Code:


program presents a number game, where user has to guesS aA
lf user enters a number greater than the saved number
8,number
[Link],
is displayed as number is too large, otherwise messagethenis meSsage
as number is too small. This process continues until the
the correct number. All this process is handled user disguesses
played
through user
exception. Here, a base class Guess is created derived from thedefined
in Exception class. Consequently, two
derived built.
ValueTooSmall and ValueTooLarge are created, inherited classes
class. from Gues8
Code: 8.7. Illustration of number game using user defined
#define Python user-defined exceptions exception.
class Guess(Exception):
wH"Base class for other exceptions"""
pass

class ValueTooSmall(Guess):
n"Raised when the input value is too small""
pass

class ValueTooLarge(Guess):
"Raised when the input value is too large"""
pass

#our main program, where user guesses a number until he/she gets it
right
# user needs to guess this number

number = 10

while True:
try:
i num =int(input("Enter a number: ")
ifi num<number:
raise ValueToo Small
elifi num> number:
raise Value'TooLarge
break
except ValueTooSmall:

214
Chapter 8: Exception Handling

print("Thisvalue is too small, try again!")


print()
except ValueTooLarge:
print("This value is too large, try again!")
print()
print("Congratulations! Youguessed it correctly. ")
Output
Enter a number:7
This value is too small, try again!
Enter a number: 20
This value is too large, try again!
Enter a number: 4
This value is too small, try again!
Enter a number: 9
This value is toosmall,try again!
Enter a number: 11
This value is too large, try again!
Enter a number: 10
Congratulations! Youguessed it correctly.

3.5. Summary
In this chapter, we have discussed about interpreting time errors (syntax
errors) and run time errors. Run time errors are also called exceptions.
Various built-in exceptions are available in Python language. However, user
can create his own exceptions for handling different circumstances, which
can occur during the execution of the program. All exception handling
constructs try, except, finally are discussed with the programming illustration
of each of them. User defined exceptions are also discussed with example.
Review Questions
1. What is an Exception? How it differs from errors in Python?

215

You might also like