2nd PUC Computer Science quick Notes |Exception Handling in Python
Complete Short Notes & Exam Preparation Guide
Based only on the NCERT textbook
Chapter Overview
While executing a Python program, the program may not execute, may produce unexpected output, or may behave abnormally. Such situations can occur due to syntax errors, runtime errors, or logical errors.
In Python, exceptions are errors that are triggered automatically. Exceptions can also be forcefully triggered and handled through program code. This chapter explains exception handling in Python programs.
Table of Contents
- 1.1 Introduction
- 1.2 Syntax Errors
- 1.3 Exceptions
- 1.4 Built-in Exceptions
- 1.5 Raising Exceptions
- 1.6 Handling Exceptions
- 1.7 Finally Clause
- 1.7.1 Recovering and Continuing with finally Clause
- Chapter Summary
- Questions & Answers
- Important Questions
- Quick Revision
- Final Revision
1.1 Introduction
Meaning
Sometimes while executing a Python program, the program does not execute at all or executes but produces unexpected output or behaves abnormally. These situations occur because of syntax errors, runtime errors, or logical errors.
1.2 Syntax Errors
Important Points
- Syntax errors are detected by the interpreter.
- When a syntax error occurs, the interpreter does not execute the program.
- The error must be rectified and the program must be saved and rerun.
- Python displays the name of the error and a short description.
- In script mode, an error dialog box can display the error information.
1.3 Exceptions
Even when a statement or expression is syntactically correct, an error may occur during its execution. Examples given in the textbook include trying to open a file that does not exist and division by zero.
Raising an Exception
When an error occurs during execution of a program, an exception is said to have been raised. The programmer needs to handle the exception so that the program does not terminate abnormally.
Important Points
- Exceptions can disrupt the normal execution of a program.
- A programmer can anticipate erroneous situations.
- Appropriate code can be included to handle those situations.
SyntaxErroris also an exception.- Other exceptions are generally generated when the program is syntactically correct.
1.4 Built-in Exceptions
Commonly occurring exceptions are usually defined in the compiler/interpreter. These are called built-in exceptions.
Python’s standard library contains built-in exceptions for commonly occurring errors. When a built-in exception occurs, the appropriate exception handler code can display the reason along with the raised exception name.
| S. No. | Name of the Built-in Exception | Explanation |
|---|---|---|
| 1 | SyntaxError | Raised when there is an error in the syntax of Python code. |
| 2 | ValueError | Raised when a built-in method or operation receives an argument having the right data type but mismatched or inappropriate values. |
| 3 | IOError | Raised when the file specified in a program statement cannot be opened. |
| 4 | KeyboardInterrupt | Raised when the user accidentally hits the Delete or Esc key while executing a program and the normal flow is interrupted. |
| 5 | ImportError | Raised when the requested module definition is not found. |
| 6 | EOFError | Raised when the end-of-file condition is reached without reading any data by input(). |
| 7 | ZeroDivisionError | Raised when the denominator in a division operation is zero. |
| 8 | IndexError | Raised when the index or subscript in a sequence is out of range. |
| 9 | NameError | Raised when a local or global variable name is not defined. |
| 10 | IndentationError | Raised due to incorrect indentation in the program code. |
| 11 | TypeError | Raised when an operator is supplied with a value of incorrect data type. |
| 12 | OverFlowError | Raised when the result of a calculation exceeds the maximum limit for numeric data type. |
1.5 Raising Exceptions
When an error is detected, the Python interpreter raises or throws an exception. Exception handlers are designed to execute when a specific exception is raised.
Programmers can also forcefully raise exceptions by using the
raise and assert statements.
- Raising an exception interrupts the normal flow of program execution.
- Control moves to the exception handler code.
- No further statement in the current block is executed after the exception is raised.
1.5.1 The raise Statement
The raise statement is used to throw an exception.
raise exception-name[(optional argument)]
The optional argument is generally a string displayed when the exception is raised.
The error raised may be a built-in exception or a user-defined exception.
Important Behaviour
- After an exception is raised, the normal execution flow is interrupted.
- The statement following the
raisestatement is not executed. - Python can display a stack traceback.
Stack Traceback
A stack traceback is a structured block of text containing information about the sequence of function calls made in the branch of execution where the exception was raised.
raise statement is used to forcefully throw an exception.
1.5.2 The assert Statement
assert statement is used to test an expression in the
program code. If the result of testing is false, an exception is raised.
It is generally used at the beginning of a function or after a function call to check for valid input.
assert Expression[,arguments]
How assert Works
- Python evaluates the expression after the
assertkeyword. - If the expression is true, execution continues.
- If the expression is false, an
AssertionErroris raised. - The exception can be handled like other exceptions.
print("use of assert statement")
def negativecheck(number):
assert(number>=0), "OOPS... Negative Number"
print(number*number)
print (negativecheck(100))
print (negativecheck(-350))
-350 is passed, an
AssertionError is raised and subsequent statements are not
executed. The message given in the textbook is
OOPS…. Negative Number.
1.6 Handling Exceptions
Exception handling helps prevent a program from crashing abruptly.
1.6.1 Need for Exception Handling
Exception handling is used in Python and in other programming languages such as C++, Java and Ruby. It is a technique for capturing runtime errors and handling them so that the program does not crash.
Important Points
- Python categorises exceptions into distinct types.
- Specific exception handlers can be created for each type.
- Exception handlers separate the main program logic from error detection and correction code.
- Code where an exception may occur can be placed in one block.
- Code for handling the exception can be placed in another block.
- The compiler or interpreter keeps track of the exact position where the error occurred.
- Both user-defined and built-in exceptions can be handled.
1.6.2 Process of Handling Exception
Exception Object
When an error occurs, Python creates an object called the exception object. It contains information about the error, such as its type, file name and position in the program where the error occurred.
Throwing an Exception
The exception object is handed over to the runtime system so that it can find appropriate code to handle the particular exception. The process of creating an exception object and handing it over to the runtime system is called throwing an exception.
Call Stack
The runtime system searches the program for an exception handler. It first searches the method in which the error occurred. If it is not found, it searches the method from which that method was called. This reverse hierarchical search continues until an exception handler is found.
Catching the Exception
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.
Logical Flow of the Textbook Process
Runtime System
The runtime system refers to the execution of statements in a program. It is a complex mechanism consisting of hardware and software that comes into action when a program written in a programming language is put into execution.
1.6.3 Catching Exceptions
Exceptions are caught in the try block and handled in the
except block.
Suspicious lines of code, where an exception may occur, are placed
inside a try block. Every try block is
followed by an except block.
try:
[program statements where exceptions might occur]
except [exception-name]:
[code for exception handling if the exception-name error is encountered]
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")
Program Behaviour
- If a non-zero denominator is entered, the quotient is displayed and the success message is displayed.
-
The
exceptclause is skipped when there is noZeroDivisionError. -
If denominator is
0, execution of thetryblock stops. -
Control moves to the
exceptblock. - The message about zero denominator is displayed.
-
The statement outside the
try...exceptblock is then executed.
Multiple except Clauses
A single piece of code may have more than one possible type of error.
Multiple except blocks can therefore be used with one
try block.
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")
Here, ZeroDivisionError and ValueError are
handled using two except blocks for a single
try block.
When an exception is raised, Python searches for a matching
except block. If no match is found, the program terminates.
except Without Specifying an Exception
If an exception occurs for which the programmer has not created a
specific handler, an except clause without specifying an
exception can be used.
This clause should be the last clause of the
try...except block.
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")
except clause without a specified exception is placed
as the last except clause.
1.6.4 try…except…else Clause
An optional else clause can be used along with the
try...except clause.
- If an exception occurs, the appropriate
exceptblock is executed. - If no error occurs, none of the
exceptblocks is executed. - In the absence of an exception, statements inside the
elseclause are executed.
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
finally clause contains statements that are always
executed, regardless of whether an exception has occurred in the
try block or not.
Important Points
finallyis optional.- It is executed whether an exception occurs or not.
- It is commonly used while working with files to ensure that the file object is closed.
- If used,
finallyis placed at the end of thetryclause. - It comes after all
exceptblocks and theelseblock.
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")
The message OVER AND OUT is displayed irrespective of
whether an exception is raised or not.
1.7.1 Recovering and Continuing with finally Clause
If an error is detected in the try block and the exception
is thrown, the appropriate except block handles it.
If no except clause handles the exception, the exception is
re-raised after the execution of the finally block.
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")
Behaviour of Program 1-7
If non-numeric data is entered, the finally block is
executed and the message OVER AND OUT is displayed.
Thereafter, the exception for which a handler is not present is
re-raised.
After execution of the finally block, Python transfers
control to a previously entered try or to the next higher
level default exception handler.
except, execution of the finally
clause does not terminate the exception. The exception continues to be
raised after execution of finally.
Overall try…except…else…finally Structure
tryCode where an exception may occur
except handler
else block
finally block → executed irrespective of exception
try block contains code where errors may occur,
except blocks contain handlers, the optional
else block executes when no exception occurs, and the
optional finally block executes regardless of whether an
exception occurs.
Chapter Summary
- Syntax errors or parsing errors occur when programming-language rules are not followed.
- Python displays the name and a short description of a syntax error.
- Program execution starts only after a syntax error is rectified.
- An exception is a Python object representing an error.
- Syntax errors are also handled as exceptions.
- An exception needs to be handled so that the program does not terminate abruptly.
- Python provides built-in exceptions for commonly occurring errors.
- Common built-in exceptions include SyntaxError, ValueError, IOError, KeyboardInterrupt, ImportError, EOFError, ZeroDivisionError, IndexError, NameError, IndentationError, TypeError and OverFlowError.
- Python raises or throws an exception when an error is encountered.
- Exception handlers are codes designed to execute when a particular exception is raised.
- Raising an exception interrupts normal program execution and transfers control to the exception handler.
raiseandassertstatements are used to raise exceptions.- Exception handling adds code that gives proper messages or instructions and prevents abrupt program crashing.
- An exception is caught when the code designed to handle it is executed.
- Exceptions are caught in the
tryblock and handled in theexceptblock. - Statements inside the
finallyblock are always executed whether an exception occurs or not.
Questions & Answers
1-Mark Questions
raise and assert statements.
ZeroDivisionError.
try block.
except block.
else block.
finally block.
2-Mark Questions
raise statement is used to throw an exception. It
interrupts the normal flow of execution and transfers control toward
exception handling.
assert statement tests an expression. If the expression
is false, an AssertionError is raised. It is generally used
to check valid input.
3-Mark Questions
except clauses can be used with one
try block. Python searches for the matching handler. If no
match is found, the program terminates unless a general
except clause is provided.
4/5-Mark Questions
try block contains statements where exceptions might
occur. The except block contains code to handle a matching
exception. The optional else block executes when no
exception occurs. The optional finally block executes
regardless of whether an exception occurs or not.
raise statement is used to throw an exception and can
include an optional argument. The assert statement tests an
expression and raises AssertionError if the expression is
false. Both are used to raise exceptions in a Python program.
Important Difference Questions
| Basis | Syntax Error | Exception |
|---|---|---|
| Meaning | Occurs when programming-language rules are not followed. | Represents an error that can occur during execution. |
| Program execution | The program does not execute until the syntax error is rectified. | The exception may disrupt normal execution and can be handled. |
| Example from chapter | SyntaxError | ZeroDivisionError, ValueError, IndexError and others. |
| Clause | Purpose |
|---|---|
try |
Contains code where an exception might occur. |
except |
Contains code to handle an exception. |
else |
Executes when no exception occurs. |
finally |
Executes regardless of whether an exception occurs or not. |
📝 Important Questions
1 Mark
- Define syntax error.
- What is an exception?
- What is a built-in exception?
- Name two statements used for raising exceptions.
- What is
ZeroDivisionError? - What is
ValueError? - What is
IndexError? - What is
NameError? - What is the use of the
finallyblock?
2 Marks
- Explain syntax errors and parsing errors.
- Explain the purpose of the
raisestatement. - Explain the
assertstatement. - Define exception handling.
- Define throwing and catching an exception.
- Explain the need for exception handling.
3 Marks
- Explain the process of handling an exception.
- Explain catching exceptions using
tryandexcept. - Explain the use of multiple
exceptclauses. - Explain the purpose of the
elseclause.
4/5 Marks
- Explain built-in exceptions in Python with their meanings.
- Explain raising exceptions using
raiseandassert. - Explain exception handling using
try...except. - Explain
try...except...elsewith the program structure. - Explain the
finallyclause and its behaviour when an exception is not handled. - Write a suitable exception-handling program for division and handle the denominator being zero.
raise,
assert, exception handling, try...except,
multiple except clauses, else,
finally, throwing/catching exceptions, and the process of
searching the call stack.
⚡ Quick Revision
Important Definitions
- Syntax error
- Exception
- Built-in exception
- Exception handling
- Throwing an exception
- Catching an exception
- Call stack
Important Terms
- SyntaxError
- ValueError
- IOError
- KeyboardInterrupt
- ImportError
- EOFError
- ZeroDivisionError
- IndexError
- NameError
- IndentationError
- TypeError
- OverFlowError
- AssertionError
Important Syntax
raise exception-name[(optional argument)]
assert Expression[,arguments]
try:
[program statements]
except [exception-name]:
[exception handling code]
Important Clauses
try→ possible exception codeexcept→ exception handlerelse→ no exceptionfinally→ always executed
Important Programs
- Use of
assertstatement - Using
try...except - Multiple
exceptclauses - Unnamed
exceptclause try...except...elsetry...except...else...finally- Recovering through
finally
Important Flow
Error → Exception Object → Runtime System → Call Stack Search → Suitable Handler → Catch Exception
If no suitable handler is found → Program execution stops.
Final Revision Section
Must Remember Before Examination
- Syntax errors occur when the rules of the programming language are not followed.
- An exception is a Python object representing an error.
- Built-in exceptions are commonly occurring exceptions defined in the compiler/interpreter.
-
raiseis used to throw an exception. -
asserttests an expression and raisesAssertionErrorwhen the expression is false. - Exception handling prevents abrupt program termination.
-
The
tryblock contains code where an exception may occur. -
The
exceptblock handles the matching exception. -
Multiple
exceptblocks can handle different exception types. -
An unnamed
exceptclause can handle an exception for which a specific handler has not been created and should be the last clause. -
The
elseblock executes when no exception occurs. -
The
finallyblock executes regardless of whether an exception occurs or not. -
If an exception is not handled by an
exceptclause, it can continue to be raised after thefinallyblock. - The call stack is searched to find a suitable exception handler.
Built-in Exceptions — One-Glance Revision
| Exception | Remember It As |
|---|---|
| SyntaxError | Error in Python syntax |
| ValueError | Correct data type but inappropriate value |
| IOError | Specified file cannot be opened |
| KeyboardInterrupt | Normal flow interrupted by user action described in the textbook |
| ImportError | Requested module definition not found |
| EOFError | End-of-file condition reached without data from input() |
| ZeroDivisionError | Denominator is zero |
| IndexError | Sequence index/subscript out of range |
| NameError | Variable name not defined |
| IndentationError | Incorrect indentation |
| TypeError | Incorrect data type supplied to an operator |
| OverFlowError | Calculation result exceeds numeric data-type limit |
Textbook Exercise — Exam Practice
- Justify the statement that every syntax error is an exception but every exception cannot be a syntax error.
-
Explain when
ImportError,IOError,NameErrorandZeroDivisionErrorare raised, with suitable examples. -
Explain the use of the
raisestatement and prepare a program to accept two numbers and display their quotient, raising an appropriate exception when the denominator is zero. -
Use an
assertstatement in the division problem to test the division expression. - Define exception handling, throwing an exception and catching an exception.
-
Explain catching exceptions using
tryandexcept. -
Complete a program using the appropriate exceptions for accepting
only integers, preventing a zero denominator, an
elseclause and afinallyclause. -
Using the math module, prepare a program involving an incorrect number
of arguments for a method such as
sqrt()orpow()and apply exception handling as required by the textbook exercise. -
Explain the use of the
finallyclause and apply it to the division exception-handling problem.
📝 This article was researched and written by Venkatesh A, Founder of verakworld.com.