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

1 Exception Handling

Chapter 1 of the Computer Science syllabus focuses on Exception Handling in Python, explaining the types of errors (syntax, runtime, and logical) that can occur during program execution. It details built-in exceptions, user-defined exceptions, and the mechanisms for raising and handling exceptions using try-except blocks, including the use of else and finally clauses. The chapter emphasizes the importance of exception handling to maintain program stability and provide user feedback during errors.

Uploaded by

roopasr2184
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)
4 views15 pages

1 Exception Handling

Chapter 1 of the Computer Science syllabus focuses on Exception Handling in Python, explaining the types of errors (syntax, runtime, and logical) that can occur during program execution. It details built-in exceptions, user-defined exceptions, and the mechanisms for raising and handling exceptions using try-except blocks, including the use of else and finally clauses. The chapter emphasizes the importance of exception handling to maintain program stability and provide user feedback during errors.

Uploaded by

roopasr2184
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/ 15

II PUC 2025-26 (New syllabus) Computer Science Chapter 1 Exception Handling

Chapter 1 Exception handling


Introduction:
• While executing a Python program, following situation may occur
• The program does not execute at all.
• The program executes but generates unexpected output.
• Behaves abnormally.
• These occur when there are syntax errors, runtime errors or logical errors in the code.
• In Python, exceptions are errors that are triggered automatically.
• Exceptions can be forcefully triggered and handled through program code.

Syntax Errors or parsing errors


• Syntax errors are detected when rules of the particular programming language are not followed 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 errors are solved.
• When a syntax error is generated while working in shell mode, Python displays the name of the error and a small description
about the error as shown in following diagram (Thonny IDE).

Diagram: A syntax error displayed in Python shell mode (Thonny IDE)

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 1


II PUC 2025-26 (New syllabus) Computer Science Chapter 1 Exception Handling

Exceptions
• An exception is a Python object that represents an error.
• Even if a statement or expression is syntactically correct, there might arise an error during its execution.
• For example,
• Trying to open a file that does not exist.
• Division by zero and so on.
• Such types of errors might alter the normal execution of the program and are called exceptions.
• When an error occurs during the execution of a program, an exception is said to be raised.
• Such an exception needs to be handled by the programmer so that the program does not terminate abnormally.
• Therefore, while designing a program, a programmer may except such error situations and handle that exception.

Built-in Exceptions
• These are the commonly occurring exceptions, which are defined in the compiler/interpreter.
• Python’s standard library is an extensive collection of built-in exceptions that deals with the commonly occurring errors
(exceptions) by providing the standardized solutions for such errors.
• 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 following table.

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 2


II PUC 2025-26 (New syllabus) Computer Science Chapter 1 Exception Handling

Name of the
S. No Explanation
Builtin exception
1 SyntaxError It is raised when there is an error in the syntax of the Python code.
It is raised when a built-in method or operation receives an argument that has the right data type
2 ValueError
but mismatched or inappropriate values.
3 IOError It is raised when the file specified in a program statement cannot be opened.
It is raised when the user accidentally hits the Delete or Esc key while executing a program due to
4 KeyboardInterrupt
which the normal flow of the program is interrupted.
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 ().
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.

Example 1:

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 3


II PUC 2025-26 (New syllabus) Computer Science Chapter 1 Exception Handling

Example 2:

Example 3:

Raising exceptions
User-defined exceptions: The exceptions created by user or programmer according to their requirements are called user-defined
exceptions.
• Programmers can raise exceptions using the raise and assert statements.
• Once an exception is raised, no further statement in the current block of code is executed.
• Raising an exception involves interrupting the normal flow execution and jumping to that part of the program (exception
handler code) which is written to handle such exceptional situations.
The raise Statement: The raise statement is used to throw an exception.
Syntax: raise exception-name [(optional argument)]
Here,
The argument is generally a string that is displayed when the exception is raised.

Example 1: raising user defined exception


>>> raise Exception ("Alert !! An exception has occurred")
Traceback (most recent call last):
File "<pyshell>", line 1, in <module>
Exception: Alert !! An exception has occurred

When an exception is raised, the message “Alert !! An exception has occurred” is displayed along with a brief description of the error.

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 4


II PUC 2025-26 (New syllabus) Computer Science Chapter 1 Exception Handling

Example 2: raising built-in exception

Output:

The assert Statement


• An assert statement is used to raise an exception after testing an expression and if that expression is false.
• 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:


assert Expression [, arguments]
Example 1:

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 5


II PUC 2025-26 (New syllabus) Computer Science Chapter 1 Exception Handling

Output:

Example 2:

Output:

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 6


II PUC 2025-26 (New syllabus) Computer Science Chapter 1 Exception Handling

Traceback stack
• This is a structured block of text that contains information about the sequence of function calls in execution of code in which
the exception was raised.

Handling exceptions
• It is the process of writing additional code in a program to give proper message or instructions to the user when an exception
occurred.
• Exceptions are handled by the programmer to avoid the program from crashing, abnormal execution.

Need for exception handling


• Python categorizes exceptions into distinct types, hence a separate code to handle that particular exception can be created.
• Exception handler separates the main logic of the program from error detection and correction code.
• The code where exception may occur and code to be executed if there a exception are written in separate block.
• The code 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 exceptions


• When an error occurs, Python interpreter creates an object called the exception object.
• This object holds details about error like error type, file name, error position inside program.
• This exception object is handed over to run time system to handle this exception.
• The run time system searches the method in which error has occurred and exception has raised for exception handler code.
• If it is not found, then run time system searches the method from which exception raised method is called.
• When a suitable exception handler code is found in call stack, it is executed by the run time system.
• If run time system could not find the exception handler then program execution stops.

List of definitions
1) Run time system
• It refers to the process of execution of statements given in the program.
• Execution of statement is complex mechanism which includes hardware and software.

2) exception object: It is an object created by python interpreter when an error occurs, which stores details about error generated.
3) Throwing an exception: process of creating an exception object and handling it over to the runtime system is called as throwing
an exception.
4) Exception handler: Its is a code segment in a program written to handle the raised exceptions.

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 7


II PUC 2025-26 (New syllabus) Computer Science Chapter 1 Exception Handling

5) Call stack: It is a list which contains all the methods, functions written in a python program.
6) Catching the exception: The process of executing a suitable exception handle code by the run time system is called as catching
expression.

Flow chart to describe exception handling process

Diagram: steps of exception handling

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 8


II PUC 2025-26 (New syllabus) Computer Science Chapter 1 Exception Handling

Catching exception
• An exception is said to be caught when a code that is described to handle a particular exception is executed.

try and except blocks


• Exceptions are caught in the try block and handled in except block.
• The suspicious code in the program where exception may occur are put inside try block.
• The code to handle the possible exceptions in try block are written inside except block.
• When there is an exception in the try block, the code next to the exception is not executed and control transferred to the except
block.
• Multiple except blocks can be used for single try block, if multiple errors are expected in try block.

Syntax of try-except block


try:
code where exception may arise
except [exception name]:
code to handle exception if generated

Example 1: single try and except block

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 9


II PUC 2025-26 (New syllabus) Computer Science Chapter 1 Exception Handling

Output 1:

Output 2:

Example 2: Multiple except blocks

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 10


II PUC 2025-26 (New syllabus) Computer Science Chapter 1 Exception Handling

Output 1:

Output 2:

Output 3:

Using of except without specifying an exception


• An except clause without specifying any exception name is used to handle exceptions without handler code.
• These type of except clauses must added as last clauses in try-except block.

Example:

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 11


II PUC 2025-26 (New syllabus) Computer Science Chapter 1 Exception Handling

Output:

try...except…else clause
• The else clause in try-except-else clause is used to execute the statements if there is no exception raised in try block.
• An except block will be executed only if some exception is raised in the try block.

Example:

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 12


II PUC 2025-26 (New syllabus) Computer Science Chapter 1 Exception Handling

Output 1:

Output 2:

Output 3:

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 13


II PUC 2025-26 (New syllabus) Computer Science Chapter 1 Exception Handling

Finally Clause
• It is an optional clause which is used to execute statements regardless of whether an exception has occurred in the try block or
not.
• It is usually used, while working with files to ensure that the file object is closed.
• Finally clause should always be written after all except blocks and the else block.

Example:

Output:

Recovering and continuing with finally clause


• If the exception is not handled by any of the except clauses, then it is re-raised after the execution of the finally block.
• After execution of finally block, Python transfers the control to a previously entered try or to the next higher level default
exception handler.

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 14


II PUC 2025-26 (New syllabus) Computer Science Chapter 1 Exception Handling

Example:

Output:

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 15

You might also like