0% found this document useful (0 votes)
0 views6 pages

Chapter 1 - Exception Handling in Python

Chapter 1 discusses exception handling in Python, explaining the types of errors that can occur during program execution, including syntax, runtime, and logical errors. It covers built-in exceptions, the process of raising and catching exceptions, and the use of try-except blocks for handling errors. The chapter also introduces the assert statement, the finally clause, and the importance of exception handling to prevent program crashes.

Uploaded by

danishsurathkal
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)
0 views6 pages

Chapter 1 - Exception Handling in Python

Chapter 1 discusses exception handling in Python, explaining the types of errors that can occur during program execution, including syntax, runtime, and logical errors. It covers built-in exceptions, the process of raising and catching exceptions, and the use of try-except blocks for handling errors. The chapter also introduces the assert statement, the finally clause, and the importance of exception handling to prevent program crashes.

Uploaded by

danishsurathkal
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/ 6

Chapter 1 :Exception Handling In Python

Introduction:
 Sometimes while executing a program the program does not execute at all
 or it 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 exception are errors that get triggered automatically .
Syntax error:
 The errors which occur when the user has not followed the rules of particular
programming language while writing a program.
 These errors are also called as parsing errors.
 When a syntax error is encountered while working in shell mode, Python displays
the name of the error and small description about the error and a suggestion to
rectify it as shown below.

Exceptions: An exception is a Python object that represents an error.


 When an error occurs during the execution of a program we say that exception has
been raised.
 Such exception needs to be handled by the programmer so that the program does not
terminate abnormally.
Built in exceptions:
 Commonly occurring exceptions are usually defined in the
compiler/interpreter. These are called built-in exceptions.
 Python’s standard library has a collection of built-in exceptions that deals
with the commonly occurring errors (exceptions).
1. SyntaxError: It is raised when there is an error in the syntax of
the Python code.
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.

1
Chapter 1: Exception handling
3. IOError: It is raised when the file specified in a program statement
cannot be opened. (Requested file cannot be found)
4. KeyboardInterrupt: It is raised when the user accidentally hits
the Delete or Esc key while executing a program.
5. ImportError: It is raised when the requested module definition is
not found.
6. EOFError: It is raised when the end of file condition is reached
without reading any data by input() function.
7. ZeroDivisionError : It is raised when the denominator in a
division operation is zero.
8. IndexError : It is raised when the index or subscript in a
sequence is out of range.
9. NameError : It is raised when a local or global variable name is
not defined.
10. IndentationError: It is raised due to incorrect indentation in
the program code.
11. TypeError: It is raised when an operator is supplied with a
value of incorrect data type.
12. OverFlowError : It is raised when the result of a calculation
exceeds the maximum limit for numeric data type.

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 commands.
 Once an exception is raised, the normal flow of the program stops and control is
transferred to the exception handler code, which is designed to handle such
exceptional situations.
The raise statement: The raise statement can be used to throw an exception.

The syntax of raise statement is:


raise exception_name [(optional argument)]

Here, argument is generally string that is to be displayed when the exception is raised.
Example 1:
>>>raise Exception( “OOPS!! An exception has occurred”)
OUTPUT:
Exception: OOPS!! An exception has occurred

The assert statement: An assert statement in Python is used to test an expression in


the program code.
 If the result after testing is false then the exception is raised.
2
Chapter 1: Exception handling
 This statement is used in the beginning of the function or after a function call to
check for valid input.

The syntax for assert statement is as follows:


assert Expression [, arguments]

 On encountering an assert statement, expression is evaluated.


 If this expression is false, an AssertionError exception is raised

Example program to illustrate the use of assert statement:

print("use of assert statement")

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

OUTPUT:
Use of assert statement
10000
None
AssertionError : OOPS.... Negative Number

 In the above example if negative value is entered, then assertion error will be thrown
and displays the message “OOPS.... Negative Number”

Handling exceptions: Writing additional code in a program to give proper messages or


instructions to the user on encountering an exception is known as exception handling.

Need for exception handling: Exception handling is a useful technique, that captures
runtime error and handles them to avoid the program from getting crashed.

Some of the important points regarding exception and their handling:


 Python categorises exception into distinct type.
 Exception handlers separate the main logic of the program from exception handler
code.
 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.

3
Chapter 1: Exception handling
Process of handling exceptions:
 When an error occurs Python interpreter creates an object called exception object.
 The object is handed over to the runtime system. This process of creating an
exception object and handing it over to the run time system is called throwing an
exception.
 The runtime system searches the entire program for exception handler.
 This hierarchical search in riverse order continue till the exception handler is found
This entire list of methods or functions is known as call stack.
 When is 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.

Catching exception: An exception is said to be caught, when a code that is designed


to handle particular exception is executed.
OR
An exception is said to be caught, when a particular exception handler code is executed.

Try .. except block: Exceptions if any are caught in the try block and handled in the
except block
 try block contains those lines of code that may give rise to an exception.
 Except block contains exception handling code.
 Every try block is followed by except block.
 When exception occurs inside try block the remaining statements in the try block are
skipped and control is transferred to except block.

The syntax of try except block is as follows:


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

Program using try except block:


print ("Practicing for try block")
try:
numerator=50

4
Chapter 1: Exception handling
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”)

Multiple except classes:


 Single piece of code might have more than one type of error.
 For handling such situations there can be multiple except block for a single try block

Program using multiple except clauses:


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

Try.. except ..else clause:


 An optional else clause can be used along with try...except block.
 An except block will be executed, only if some exception is raised in the try block.
 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: 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)

5
Chapter 1: Exception handling
Finally clause:
 The try statement can also have an optional finally clause.
 The statements inside finally block are always executed regardless of whether an
exception has occurred in the try block or not.
 finally clause is used for while working with files to ensure that the file object is
closed.
 Finally clause should always be placed at the end of try clause, after all except blocks
and the else block.

Program using finally clause:


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

ASSIGNMENT QUESTIONS:
1. What is an exception in Python?
2. Explain any five built in exceptions in Python.
3. What is meant by throwing(raising) an exception?
4. What is the use of raise and assert statements in python? Give the syntax
and example for each.
5. What is exception handling ?
6. What do you mean by catching exception?
7. What is the use of try.. except block? Give the syntax and an example.
8. What is the use of multiple except blocks in try..except block?
9. Explain the use of try…except…else clause with an example.
10. What is the use of finally clause? Where is it placed in the program, if used?

6
Chapter 1: Exception handling

You might also like