Chapter – 1 : Exception Handling in Python
Q.1. What happens when errors occur in Python programs?
Answer: Sometimes, while executing a Python program:
The program may not execute at all, or
It may execute but produce unexpected output or behave abnormally.
Q.2. What are exceptions in Python?
Answer: In Python, exceptions are errors that occur during runtime.
Q.3. What are syntax errors, and how does Python handle them?
Answer :
Syntax errors (also called parsing errors) occur when the rules of a
programming language are not followed
When a syntax error is encountered, Python does not execute the programme .
OR Syntax errors are the errors which occur when there is an error in the syntax
of the code
Handling Syntax Errors
In Shell Mode: Python displays the name of the error and a brief description of the
issue.
In Script Mode: A dialog box appears, showing the error name and a short explanation.
Q.4. What are the types of errors in Python, and how are syntax errors displayed?
Answer :Errors in Python may cause the program to stop executing, produce incorrect
output, or behave abnormally.
There are three types of errors:
Syntax Errors (Parsing Errors)
Runtime Errors (Exceptions)
Logical Errors (Semantic errors)
How Syntax Errors are displayed:
In Shell Mode: Python displays the name of the error and a brief description
of the issue.
In Script Mode: A dialog box appears showing the error name and a short
explanation.
Q.5. What are exceptions in Python, and why is exception handling important?
Answer: An exception is a Python object that represents an error occurring during
execution (even when the code is syntactically correct).
Examples of Exceptions:
Trying to open a file that doesn’t exist
Division by zero
When an exception occurs, it is said to be raised and may disrupt program execution.
Why Exception Handling Is Important:
Prevents abnormal termination of the program.
Allows programmers to anticipate errors and write exception-handling code to
handle these situations gracefully.
Q.6. What are built-in exceptions in Python, and how do they work?
Answer: Built-in exceptions are predefined exceptions that commonly occur during
program execution. These are part of Python's standard library and handle common errors
by displaying the exception name and the reason for the error.
When a built-in exception is raised, the appropriate exception handler is executed, and
the programmer can take further action to resolve the issue.
Aurobindo Composite PU College 1
Chapter – 1 : Exception Handling in Python
Q.7. What are some commonly occurring built-in exceptions in Python?
Answer: The following are some common built-in exceptions:
Note: Programmers can create user-defined exceptions to handle errors specific to their
program's requirements.
Q. 8. How are exceptions raised in Python, and what happens when they are raised?
Answer:
Python raises exceptions when errors occur, interrupting normal program flow.
Exception handlers handle specific errors when they are raised.
Programmers can also raise exceptions manually using the raise and assert
statements.
Once an exception is raised, the statements after it in the block won’t be executed.
Q.9. What is the raise statement, and how is it used?
Answer: The raise statement throws an exception manually.
Syntax: raise ExceptionName("Optional error message")
Example: raise Exception("OOPS: An Exception has occurred")
Q.10. What is the assert statement, and how does it work?
Answer: The assert statement tests an expression. If the expression is False, it raises an
AssertionError.
Syntax: assert Expression, "Error message"
Example:
def check_positive(num):
assert num >= 0, "OOPS... Negative Number"
print(num * num)
check_positive(100) # Works fine
check_positive(-10) # Raises AssertionError with the message
Aurobindo Composite PU College 2
Chapter – 1 : Exception Handling in Python
When the input is negative, AssertionError is raised, and the remaining statements won’t
run.
Q.11. What is exception handling, and why is it important?
Answer: Exception handling involves writing extra code to manage exceptions and
prevent the program from crashing abruptly. It helps provide meaningful error messages
or instructions to the user.
Importance:
Avoids program crashes during runtime errors.
Allows handling of both built-in and user-defined exceptions.
Separates the main program logic from the error-handling code.
Helps detect the exact error location and type using exception handlers.
Q.12. Explain the process of exception handling in Python. What is throwing and
catching exceptions?
Answer:
When an error occurs, Python creates an exception object containing details like
the error type, file name, and error position.
This object is passed to the runtime system to find the appropriate exception
handler.
If the exception handler is not found, the run time system searches for the
exception handler in the methods present in call stack.
If the exception handler is found, it will be executed otherwise the program
terminates.
The process of creating an object and handing it over to the run time system is
called throwing an exception.
The process of executing a suitable exception handler is known as catching the
exception.
Q.13. What is catching an exception in Python, and how is it done? OR Explain
catching exception using try and except block with syntax.
Aurobindo Composite PU College 3
Chapter – 1 : Exception Handling in Python
Answer: The process of executing a suitable exception handler is known as catching the
exception.
Python uses the try and except blocks to catch exceptions.
Syntax:
try:
[program statements where exceptions might occur]
except [exception-name]:
[code to handle the exception if encountered]
How it Works:
The try block contains the code where exceptions may occur.
If an exception occurs, control is transferred to the corresponding except block,
and the rest of the try block is skipped. The except block contains the code to handle
exceptions.
If no exception is encountered, the except block is ignored, and the program
continues normally.
Q.14. What are multiple except blocks, and how do they work in Python?
Answer: A single try block may handle multiple types of exceptions by using several
except blocks, each designed to handle a specific error.
Example (Multiple except blocks):
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")
If ZeroDivisionError occurs, the matching except block handles it.
If ValueError occurs, the corresponding except block handles it.
Q.15. How can you handle unknown exceptions in Python?
Answer: When an exception occurs that is not specifically handled, you can catch it
using a generic except clause without specifying any exception type. This should always
be placed last after other except clauses.
Example (Generic exception handler):
try:
numerator = 50
denom = int(input("Enter the denominator: "))
print(numerator / denom)
except ValueError:
print("Only INTEGERS should be entered")
except:
print("OOPS... SOME EXCEPTION RAISED")
If any unspecified error occurs, the generic except block will handle it.
Q.16. Explain the purpose of the else clause in exception handling. Write a program
to demonstrate its use.
Answer: In Python, the else clause is used with the try...except block to specify a block
of code that runs only if no exceptions occur in the try block.
Aurobindo Composite PU College 4
Chapter – 1 : Exception Handling in Python
If an exception is raised, the except block is executed.
If no exception is raised, the else block is executed after the try block.
Program Example:
try:
numerator = 50
denom = int(input("Enter the denominator: "))
quotient = numerator / denom
except ZeroDivisionError:
print("Denominator cannot be zero.")
except ValueError:
print("Enter a valid integer.")
else:
print("The result is:", quotient)
In this example:
If the user enters a valid, non-zero denominator, the else block displays the result.
If the user enters zero or a non-integer, the corresponding except block is
executed.
Q.17. What is the finally clause in Python? Explain with an example.
Answer: The finally clause in Python is always executed regardless of whether an
exception has occurred in the try block or not It is often used for clean-up operations,
such as closing files or releasing resources.
Example:
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")
Explanation: In this example, the message "OVER AND OUT" will be displayed
whether or not an exception occurs. This ensures proper clean-up and smooth program
execution.
Q.18. What happens when an exception is raised but not handled in the try block?
Explain with the finally clause.
Answer: If an exception is raised in the try block but not handled by any of the except
clauses, the finally block will still execute before the exception is re-raised. This ensures
that essential cleanup (like closing files) happens before the error propagates further.
Example:
print("Practicing for try block")
try:
numerator = 50
denom = int(input("Enter the denominator: "))
Aurobindo Composite PU College 5
Chapter – 1 : Exception Handling in Python
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")
Explanation:
If the input is 0, the ZeroDivisionError is handled by the except block, and
"OVER AND OUT" is displayed.
If non-numeric input is given (e.g., "abc"), a ValueError occurs, which is not
handled. However, "OVER AND OUT" will still be printed due to the finally
block, and the unhandled exception will be re-raised afterward.
Summary:
try block: Code where exceptions might occur.
except block: Handles specific exceptions.
else block: Executes if no exception is raised.
finally block: Executes whether or not an exception occurs.
Q.19. Define a. Exception handling. b. Throwing an exception.
c. Catching an exception d. IndexError. e. IndentationError
Answer: a. The process of writing additional code in a program to give proper messages
or instructions to the user when an exception occurs is known as exception handling.
b. The process of creating an exception object and handing it over to the runtime system
is called throwing an exception.
c. The process of executing a suitable exception handler is known as catching exception.
d. IndexError is raised when the index in a sequence is out of range.
e. IndentationError is raised due to in correct indentation in the program co
Aurobindo Composite PU College 6