Exception Handling
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.
Examples for Zero Division Error, Name Error & Type Error:
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.
So, raising an exception involves interrupting the normal flow execution of program and
jumping to that part of the program (exception handler code) which is written to handle
such exceptional situations.
• The execution of the program will start only after the syntax error is rectified.
• An exception is a Python object that represents an error.
• Syntax errors are also handled as exceptions.
• The exception needs to be handled by the programmer so that the program does not
terminate abruptly.
• When an exception occurs during execution of a program and there is a built-in exception
defined for that, the error message written in that exception is displayed. The programmer
then has to take appropriate action and handle it.
• Some of the commonly occurring built-in exceptions are SyntaxError, ValueError, IOError,
KeyboardInterrupt, ImportError, EOFError, ZeroDivisionError, IndexError, NameError,
IndentationError, TypeError,and OverFlowerror.
Syntax Error:
These are the errors resulting out of violation of programming language’s grammar rules.
All syntax errors are reported during compilation. Example:
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.”
Observe that there is nothing wrong with the program syntax, it is only when we try to
divide an integer with zero , an exception is generated.
Exception Examples:
What is Exception Handling?
Exception handling in Python 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. In Python, exception
handling is implemented using a try-except block
Exception Handling using. try and except Block:
The try and except block in Python is a way to handle exceptions or errors that may occur
during code execution. This mechanism prevents the program from crashing by allowing it
to continue running even if an error is encountered.
In a try block, you write the code that might raise an exception. If an exception occurs, the
code execution jumps to the corresponding except block, where you can handle the error or
take alternative actions.
When syntax error is encountered, Python displays the name of the error and a small
description about the error.
Exceptions:
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 disrupt the normal execution of the program and are called exceptions.
An exception is a Python object that represents an error. When an error occurs during the
execution of a program, an exception is said to have been 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 anticipate such erroneous
situations that may arise during its execution and can address them by including
appropriate code to handle that exception.
Built-In Exceptions:
Commonly occurring exceptions are usually defined in the compiler/interpreter. These are
called built-in exceptions.
Summary:
• When an error is encountered in a program, Python interpreter raises or throws an
exception.
• Exception Handlers are the codes that are designed to execute when a specific exception
is raised.
• Raising an exception involves interrupting the normal flow of the program execution and
jumping to the exception handler.
• Raise and assert statements are used to raise exceptions.
• The process of exception handling involves writing additional code to give proper
messages or instructions to the user. This prevents the program from crashing abruptly. The
additional code is known as an exception handler.
• An exception is said to be caught when a code that is designed to handle a particular
exception is executed.
• An exception is caught in the try block and handles in except block.
Practice Programs
1. Write a Python program that takes two numbers as input from the user and calculates the
quotient of the two numbers. Handle the exceptions that may occur during the program
execution, such as invalid input or division by zero.
2. Write a Python program that reads a file and displays its contents on the screen. Handle
the exceptions that may occur during the program execution, such as the file not found error
or file reading error.
3. Write a Python program that takes a list of integers as input from the user and calculates
the average of the numbers. Handle the exceptions that may occur during the program
execution, such as invalid input or division by zero.
4. Write a Python program that reads a CSV file and displays its contents on the screen.
Handle the exceptions that may occur during the program execution, such as the file not
found error or file reading error.
5. Write a Python program that takes a string as input from the user and converts it to an
integer. Handle the exceptions that may occur during the program execution, such as invalid
input or string conversion error.
6. Write a Python program that takes a list of numbers as input from the user and finds the
maximum and minimum numbers in the list. Handle the exceptions that may occur during
the program execution, such as invalid input or empty list error.
7. Write a Python program that reads a file and writes its contents to another file. Handle the
exceptions that may occur during the program execution, such as the file not found error or
file reading/writing error.
8. Write a Python program that takes two strings as input from the user and concatenates
them. Handle the exceptions that may occur during the program execution, such as invalid
input or string concatenation error.
9. Write a Python program that reads a text file and counts the number of words in it.
Handle the exceptions that may occur during the program execution, such as the file not
found error or file reading error.
10. Write a Python program that takes a string as input from the user and reverses it. Handle
the exceptions that may occur during the program execution, such as invalid input or string
reversal error.