0% found this document useful (0 votes)
4 views17 pages

Chapter - Exception File Handling in Python

The document provides an overview of exception handling in Python, detailing types of errors such as syntax and runtime errors, and explaining the concept of exceptions. It covers built-in exceptions, the process of raising and handling exceptions using try-except blocks, and the use of finally and else clauses. Additionally, it emphasizes the importance of exception handling in maintaining program stability and robustness.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views17 pages

Chapter - Exception File Handling in Python

The document provides an overview of exception handling in Python, detailing types of errors such as syntax and runtime errors, and explaining the concept of exceptions. It covers built-in exceptions, the process of raising and handling exceptions using try-except blocks, and the use of finally and else clauses. Additionally, it emphasizes the importance of exception handling in maintaining program stability and robustness.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Computer Science – Exception Handling in Python

Chapter - 01
Exception Handling in Python

1.1 Introduction

Sometimes while executing a Python program, 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, runtime errors or logical errors in the code. In Python, exceptions are
errors that get triggered automatically. However, exceptions can be forcefully triggered and
handled through program code.

1.2 Types of Error :

An error is a term which is used to describe any issue that arises unexpectedly that cause
a computer do not functioning properly. The process of finding and eliminating the errors is
called Debugging.
In Python We have 2 types of Errors:
1. Syntax Error / Compile-Time Error
2. Runtime Error

Syntax Error / Compile-Time Error:

These are the errors resulting out of violation of programming language‟s grammar rules. All
syntax errors are reported during compilation. These errors are also known as parsing errors.

When a syntax error is


encountered while working in
shell mode, Python displays the
name of the error and a small
description about the error as
shown in Figure 1.1.

Note: All syntax errors are


reported during compilation.

1 SOWMYA RANI G S, LECTURER, DEPT. OF COMPUTER SCIENCE, CHITRADURGA


Computer Science – Exception Handling in Python

Run-time Errors:

The errors that occur during execution of program are called runtime-error because of
unexpected situations. Such errors are handled through exception handling. We get Runtime
Errors because of programming logic, invalid input, memory related issues etc.. For every
Runtime-Error, Python is providing corresponding exception class is available.

Example: KeyError, IndexError, ValueError, NameError etc ....

At the time of execution of a program if any Runtime-Error is occur then internally


corresponding Runtime-Error representation classes object will be created.

NOTE: If python program doesn't contain the code to handle that exception object then
our program execution will be terminated abnormally.

1.3 Exception :

Exceptions are unexpected events or errors that occur during the execution of a program,
such as a division by zero or accessing an invalid memory location. These events can lead to
program termination or incorrect results.

“It is an exceptional event that occurs during runtime and causes normal program flow to be
disrupted.”

Some common examples of Exceptions are :

 Divide by zero errors


 Accessing the elements of an array beyond it s range
 Invalid input
 Opening a non-existent file
 Heap memory exhausted

Exception Example -1:

2 SOWMYA RANI G S, LECTURER, DEPT. OF COMPUTER SCIENCE, CHITRADURGA


Computer Science – Exception Handling in Python

Exception Example -2:

Exception Example -3:

3 SOWMYA RANI G S, LECTURER, DEPT. OF COMPUTER SCIENCE, CHITRADURGA


Computer Science – Exception Handling in Python

1.4 Built-In Exceptions :


Built-in exceptions are pre-defined error classes in Python that handle errors and exceptional
conditions in programs. They are derived from the base class "BaseException" and are part of
the standard library.
On the occurrence of any built-in exception, the appropriate exception handler code is
executed which displays the reason along with the raised exception name. The programmer
then has to take appropriate action to handle it.
Some of the commonly occurring built-in exceptions that can be raised in Python are
explained in Table 1.1.
Table 1.1 Built-in exceptions in Python
Exception Name Description
BaseException The base class for all built-in exceptions.
Exception The base class for all non-exit exceptions.
ArithmeticError Base class for all errors related to arithmetic operations.
ZeroDivisionError Raised when a division or modulo operation is performed with zero as the
divisor.
AssertionError Raised when an assert statement fails.
AttributeError Raised when an attribute reference or assignment fails.
IndexError Raised when a sequence subscript is out of range.
KeyError Raised when a dictionary key is not found.
MemoryError Raised when an operation runs out of memory.
NameError Raised when a local or global name is not found.
TypeError Raised when an operation or function is applied to an object of inappropriate
type.
ValueError Raised when a function receives an argument of the right type but
inappropriate value.
ModuleNotFoundError Raised when a module cannot be found.

4 SOWMYA RANI G S, LECTURER, DEPT. OF COMPUTER SCIENCE, CHITRADURGA


Computer Science – Exception Handling in Python

IOError Raised when an I/O operation (like reading or writing to a file) fails.
FileNotFoundError Raised when a file or directory is requested but cannot be found.
StopIteration Raised when the next() function is called and there are no more items in an
iterator.
RuntimeError Raised when a general error occurs in the program.
SyntaxError Raised when there is an error in the syntax of the code.
IndentationError Raised when there is an indentation error in the code.

1.5 Raising Exceptions :


Each time an error is detected in a program, the Python interpreter raises (throws) an
exception. Exception handlers 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.

1.5.1 The Raise Statement

The raise statement can be used to throw an exception. The syntax of raise statement is:
raise exception-name[(optional argument)]
The argument is generally a string that is displayed when the exception is raised.

In the below code, we check if an integer is even or odd. if the integer is odd an exception is
raised. a is a variable to which we assigned a number 5, as a is odd, then if checks if it‟s an
odd integer, if it‟s an odd integer then an error is raised.
a=5
if a % 2 != 0:
raise Exception("The number shouldn't be an odd integer")

Output:

Note: In this case, the user has only raised the exception but has not displayed any error
message explicitly. In Figure 1.6, since the value of variable length is greater than the
length of the list numbers, an IndexError exception will be raised. The statement

5 SOWMYA RANI G S, LECTURER, DEPT. OF COMPUTER SCIENCE, CHITRADURGA


Computer Science – Exception Handling in Python

following the raise statement will not be executed. So the message “NO EXECUTION”
will not be displayed in this case.

1
Following are the advantages of Raise statement
 It helps us raise error exceptions when we may run into situations where
execution can't proceed.
 It helps us raise error in Python that is caught.
 Raise allows us to throw one exception at any time.
 It is useful when we want to work with input validations.
5.2 The 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. This statement is
generally used in the beginning of the function or after a function call to check for valid
input.
The 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 AssertionError exception is raised
which can be handled like any other exception.
In the following example, we are using assertions to ensure that the variable
"num" falls within the valid range of "0" to "100". If the assertion fails, Python raises an
"AssertionError", preventing further execution of the subsequent print statement –

6 SOWMYA RANI G S, LECTURER, DEPT. OF COMPUTER SCIENCE, CHITRADURGA


Computer Science – Exception Handling in Python

print('Enter marks out of 100:')


num = 75
assert num >= 0 and num <= 100
print('Marks obtained:', num)

num = 125
assert num >= 0 and num <= 100
print('Marks obtained:', num) # This line won't be reached if assertion fails

Following is the output of the above code −

Enter marks out of 100:


Marks obtained: 75
Traceback (most recent call last):
File "/home/cg/root/66723bd115007/main.py", line 7, in <module>
assert num >= 0 and num <= 100
AssertionError

1.6 HANDLING EXCEPTIONS

Exception handling is a mechanism used to handle runtime errors that occur during the
execution of a Python program. Exception handling allows a program to gracefully handle such
exceptions and recover from errors by taking corrective actions instead of terminating abruptly.

1.6.1 Need for Exception Handling

Exception handling is a useful technique that helps in capturing runtime errors and
handling them so as to avoid the program getting crashed. Following are some of the important
points regarding exceptions and their handling:

 Python categorizes exceptions into distinct types so that specific exception handlers (code
to handle that particular exception) 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 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.

7 SOWMYA RANI G S, LECTURER, DEPT. OF COMPUTER SCIENCE, CHITRADURGA


Computer Science – Exception Handling in Python

1.6.2 Process of Handling Exception

Following are the steps in exception handling process

1. 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. (Hit an exception)
2. Python runtime system throwing the exception object (throw an exception)
3. The object is handed over to the runtime system so that it can find an appropriate code to
handle this particular exception. (catch an exception)
4. The runtime system searches the entire program for a block of code, called the exception
handler. It 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. When a suitable handler is found, 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, then
the program execution stops.(handle an exception)

8 Mr. Guruprasad T R, Faculty, Dept. Of CS, Namma Experts PU College, Chitradurga


Computer Science – Exception Handling in Python

1.6.3 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 handled in the except block.

The suspicious lines of codes are put inside a try 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.

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.

The syntax of try … except clause is as follows:

try:
[ program statements where exceptions might occur]
except [exception-name]:
[ code for exception handling if the exception-name error is encountered]

Write a program to ensure that an integer is entered as input and in case any other value is entered, it
displays a message – „Not a valid integer‟

9 SOWMYA RANI G S, LECTURER, DEPT. OF COMPUTER SCIENCE, CHITRADURGA


Computer Science – Exception Handling in Python

Second Argument of the Exception Block:

We can also provide a second argument (optional) for the except block, which gives a reference
to the exception object.

try:
#code
except <ExceptionName> as <Argument> :
#code for error handling here

Handling Multiple Errors :

Handling multiple exceptions in Python allows a single try-except block to handle different types
of exceptions using multiple except blocks. This allows a program to handle various types of
errors that may occur during runtime and take corrective measures accordingly.

In a try-except block, each except block is associated with a specific exception type, and the
block containing the code to handle that exception is executed if the corresponding exception
occurs in the try block. By handling multiple exceptions, programmers can write more robust and
less error-prone code.

Program to handle multiple exceptions:

10 SOWMYA RANI G S, LECTURER, DEPT. OF COMPUTER SCIENCE, CHITRADURGA


Computer Science – Exception Handling in Python

1.6.4 try . . . except…else clause

We can put an optional else clause along with the try… except clause. An except block will be
executed only if some exception is raised in the try block. But if there is no error then none of the
except blocks will be executed. In this case, the statements inside the else clause will be
executed.

Program along with its output explains the use of else block with the try… except block.

11 SOWMYA RANI G S, LECTURER, DEPT. OF COMPUTER SCIENCE, CHITRADURGA


Computer Science – Exception Handling in Python

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)

1.7 FINALLY Clause :

The finally block is a part of the try-except block in Python that contains the code that is
executed regardless of whether an exception is raised or not.

The syntax of the try-except-finally block is as


follows:

The try block contains the code that may raise an


exception. If an exception occurs, the control is
transferred to the corresponding except block,
which contains the code to handle the exception.
The finally block contains the code that is
executed after the try-except blocks, regardless of whether an exception occurred or not.

Example : Program using finally block

12 SOWMYA RANI G S, LECTURER, DEPT. OF COMPUTER SCIENCE, CHITRADURGA


Computer Science – Exception Handling in Python

13 SOWMYA RANI G S, LECTURER, DEPT. OF COMPUTER SCIENCE, CHITRADURGA


Computer Science – Exception Handling in Python

14 SOWMYA RANI G S, LECTURER, DEPT. OF COMPUTER SCIENCE, CHITRADURGA


Computer Science – Exception Handling in Python

15 SOWMYA RANI G S, LECTURER, DEPT. OF COMPUTER SCIENCE, CHITRADURGA


Computer Science – Exception Handling in Python

19. What will be the output of the following Python code?


lst = [1, 2, 3]
lst[3]
a) NameError
b) ValueError
c) IndexError
d) TypeError
20. What will be the output of the following Python code?
t[5]
a) IndexError
b) NameError
c) TypeError
d) ValeError
21. What will be the output of the following Python code, if the time module has already been
imported? 4 + '3'
a) NameError
b) IndexError
c) ValueError
d) TypeError

16 SOWMYA RANI G S, LECTURER, DEPT. OF COMPUTER SCIENCE, CHITRADURGA


Computer Science – Exception Handling in Python

22. What will be the output of the following Python code?


int('65.43')
a) ImportError
b) ValueError
c) TypeError
d) NameError
23. Identify the type of error in the following Python
codes? Print(“Good Morning”)
print(“Good night)
a) Syntax, Syntax
b) Semantic, Syntax
c) Semantic, Semantic
d) Syntax, Semantic
24. Which of the following is not a standard exception in Python?
a) NameError
b) IOError
c) AssignmentError
d) ValueError
25. exceptions are raised as a result of an error in opening a particular file.
a) ValueError
b) TypeError
c) ImportError
d) IOError
26. Which of the following blocks will be executed whether an exception is thrown or not?
a) except
b) else
c) finally
d) assert

17 SOWMYA RANI G S, LECTURER, DEPT. OF COMPUTER SCIENCE, CHITRADURGA

You might also like