KnowledgeBoat Logo
OPEN IN APP

Chapter 3

Exception Handling

Class 12 - Computer Science with Python Preeti Arora



Fill in the Blanks

Question 1

On encountering a syntax error, the interpreter does not execute the program unless these errors are removed by the user.

Question 2

When a number is divided by 0, ZeroDivisionError error is raised.

Question 3

Exception is a Python object that represents an error.

Question 4

NameError error is raised when a local or global variable is not defined.

Question 5

The try block holds the code to be run and checked for any error, if exists.

State True or False

Question 1

ValueError occurs due to wrong indentation in a program.

Answer

False

Reason — A ValueError is raised when a built-in operation or function receives an argument that has the right type but an inappropriate value.

Question 2

Exception and error are the same objects.

Answer

False

Reason — An Error is a bug in the code that causes irregular output or stops the program from executing whereas an Exception is an irregular unexpected situation occurring during execution on which programmer has no control.

Question 3

Exceptions are caught using try block.

Answer

True

Reason — Exceptions are caught using the try block because it encapsulates code that might raise exceptions. If any code within the try block causes an error or exception, the program will transfer control to the corresponding except block to handle the exceptional situation.

Question 4

The order of exception handling in Python is try, followed by except, and then finally.

Answer

True

Reason — The order of exception handling in Python is as follows: first, the try block contains the code that may raise an exception. Then, the except block is used to handle specific types of exceptions that may occur within the try block. Finally, the finally block, if present, is executed whether an exception is raised or not.

Question 5

Catch is a part of exception handling.

Answer

False

Reason — In Python, the 'except' block is used for exception handling, not the keyword 'catch'. The 'except' block is used to catch and handle exceptions that occur during program execution.

Multiple Choice Questions

Question 1

The errors encountered when a user violates the syntax of a programming language while writing a code are termed as ............... .

  1. Compile time error
  2. Logical error
  3. Runtime error
  4. Exception

Answer

Compile time error

Reason — When a user violates the syntax of a programming language while writing code, it results in a compile-time error. These errors are detected by the compiler during the compilation process and prevent the program from being compiled successfully.

Question 2

An interrupt or forced disruption that occurs when a program is run or executed is termed as ............... .

  1. Compile time error
  2. Exception
  3. Runtime error
  4. Logical error

Answer

Exception

Reason — An exception is an interrupt or disruption that occurs during the execution of a program. When an exception occurs, it interrupts the normal flow of the program and may cause the program to terminate abruptly if not handled properly.

Question 3

Which of the following keywords are not specific to exception handling?

  1. try
  2. except
  3. else
  4. finally

Answer

else

Reason — The 'else' keyword in Python is not specific to exception handling but rather plays a role in conditional statements and control flow structures. On the other hand, in exception handling constructs, the main keywords are 'try,' 'except,' and 'finally.

Question 4

Which block is a mandatory block in exception handling process?

  1. try
  2. except
  3. finally
  4. else

Answer

try

Reason — The try block is a mandatory component of the exception handling process because it encapsulates code that might raise exceptions, allowing them to be caught and handled effectively.

Question 5

Forced exceptions are indicated using which of the following keywords?

  1. try
  2. except
  3. finally
  4. raise

Answer

raise

Reason — The raise statement allows the program to force a specified exception to occur at runtime. When a program encounters an abnormal condition during execution, an object of this exception is created and then thrown or raised to the code responsible for catching and handling it.

Assertions and Reasons

Question 1

Assertion (A): Exception handling handles all types of errors and exceptions.

Reasoning (R): Exception handling is responsible for handling anomalous situations during the execution of a program.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
Exception handling in Python allows users to catch and manage various types of errors and exceptions that may occur during program execution. It is designed to handle unexpected or anomalous situations, such as errors or exceptions, that may arise while a program is running.

Question 2

Assertion (A): Exception handling code is separate from normal code.

Reasoning (R): Program logic is different while exception handling code uses specific keywords to handle exceptions.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
Exception handling code is separate from normal code in programming languages. Exception handling code uses specific constructs like try, except, finally (in Python). Exception handling involves a different flow of control compared to regular program logic. When an exception occurs, the program jumps to the corresponding exception handling block (such as the except block in Python) rather than following the normal sequence of statements.

Question 3

Assertion (A): Exception handling code is clear and block based in Python.

Reasoning (R): The code where unexpected runtime exception may occur is separate from the code where the action takes place when an exception occurs.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
In Python, the structure of exception handling using clear and distinct blocks like try, except, and finally helps in organizing code. It separates the code where exceptions might occur (within the try block) from the code responsible for handling those exceptions (within the except and finally blocks).

Question 4

Assertion (A): No matter what exception occurs, you can always make sure that some common action takes place for all types of exceptions.

Reasoning (R): The finally block contains the code that must execute.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
The 'finally' block contains code that must execute, irrespective of whether an exception is raised. This ensures that some common action takes place for all types of exceptions, no matter which exception occurs.

Solutions to Unsolved Questions

Question 1

What all can be the possible outputs of the following code?

def myfunc (x=None) :
    result = "" 
    if x is None:
       result = "No argument given"
    elif x == 0: 
       result = "Zero"
    elif 0 < x <= 3:
       result = "x is between 0 and 3"
    else:
       result = "x is more than 3"
    return result 
c = myfunc (3.5) 
    print (c)

Answer

The incorrect indentation of the print statement will cause an indentation error when the code is executed.

Explanation

The corrected code is as follows:

def myfunc(x = None) :
    result = "" 
    if x is None:
       result = "No argument given"
    elif x == 0: 
       result = "Zero"
    elif 0 < x <= 3:
       result = "x is between 0 and 3"
    else:
       result = "x is more than 3"
    return result 
c = myfunc(3.5) 
print(c)
Output
x is more than 3

Working of the code:

The code defines a function myfunc that takes an argument x, which defaults to None. Inside the function, it checks the value of x using a series of if-elif-else conditions. If x is None, it sets the result to "No argument given." If x is 0, it sets the result to "Zero." If x is greater than 0 but less than or equal to 3, it sets the result to "x is between 0 and 3." Otherwise, if x is greater than 3, it sets the result to "x is more than 3." The function then returns the result. In the provided code, the function is called with the argument 3.5, which falls into the last else condition, resulting in the output "x is more than 3" being stored in variable c and printed.

Question 2

List the situation(s) in which the following errors occur:

(a) IOError

(b) NameError

(c) ValueError

(d) TypeError

Answer

(a) IOError — This error is raised if the requested file cannot be opened, or failure of I/O operation.

(b) NameError — This error is raised when an identifier is not found in the local or global namespace.

(c) ValueError — This error is raised when a built-in operation or function receives an argument that has the right type but an inappropriate value.

(d) TypeError — This error is raised when an operation or function is attempted that is invalid for the specified data type.

Question 3

Name three run-time errors that occur during Python program execution.

Answer

TypeError, ZeroDivisionError, IndexError are the three run-time errors that occur during Python program execution.

Question 4

What is the difference between an error and exception?

Answer

An Error is a bug in the code that causes irregular output or stops the program from executing whereas an Exception is an irregular unexpected situation occurring during execution on which programmer has no control.

Question 5

How can you handle an exception in Python? Write sample code to illustrate it.

Answer

In Python, we can handle exceptions using the try-except block. It includes the following steps:

  1. Firstly, the moment an error occurs the state of execution of the program is saved.
  2. Normal flow of the program is interrupted.
  3. A special function or piece of code known as exception handler is executed.
  4. Execution of the program is resumed with the previously saved data.

Here's an example of how to handle an exception:

def divide_numbers(x, y):
    try:
        result = x / y
    except ZeroDivisionError:
        print("Error: Division by zero is not allowed.")
    else:
        print("Division result:", result)
    finally:
        print("End of division operation.")

divide_numbers(10, 2) 
divide_numbers(10, 0)  
Output
Division result: 5.0
End of division operation.
Error: Division by zero is not allowed.
End of division operation.

This Python code defines a function divide_numbers that performs division between two numbers x and y. It uses a try-except block to handle exceptions that may arise during division, specifically the ZeroDivisionError. If a division by zero occurs, the program prints an error message indicating that division by zero is not allowed. Otherwise, if the division operation succeeds without any exceptions, it prints the result of the division. The finally block is executed in both cases, indicating the end of the division operation.

Question 6

Name some common built-in exceptions in Python.

Answer

Some common built-in exceptions in Python are NameError, TypeError, ValueError, ZeroDivisionError, AttributeError, KeyError, IndentationError, IOError, IndexError, EOFError, SyntaxError and RuntimeError.

Question 7

What does the finally clause produce in a try...except block?

Answer

The 'finally' clause in a 'try-except' block is executed regardless of whether an exception occurs in the 'try' block or not. Its primary purpose is to ensure that certain actions or cleanup operations are performed, before the program exits or moves on to the next code block.

Question 8

Write syntax of raise statement.

Answer

The syntax of raise statement is:

raise[exception name [, message/argument][, traceback]]

Question 9

Differentiate between IOError and IndexError.

Answer

IOErrorIndexError
This error is raised if the file requested cannot be opened, or failure of I/O operation.This error is raised when an index is not found in a sequence, i.e., out of range or out of bounds.
Examples of situations that can raise an IOError include: Opening a non-existent file for reading or writing, trying to read from a file that has been closed.Examples of situations that can raise an IndexError include: Accessing an index that is beyond the length of a list or tuple, trying to access a character in a string at an index that is outside the valid range of indices, using a negative index that is too large for the sequence.

Question 10

Show how to modify the following code so that an error is printed if the number conversion is not successful:

val = input("Enter a number")  
pval = int(val)

Answer

val = input("Enter a number: ")
try:
    pval = int(val)
except ValueError:
    print("Error: Conversion to integer failed.")
Output
Enter a number: 23

Enter a number: python
Error: Conversion to integer failed.
Explanation

In this modified code the input function prompts the user to enter a number. The try block attempts to convert the input value to an integer using int(val). If the conversion is successful, pval will hold the integer value. If the conversion raises a ValueError (e.g., if the input is not a valid integer), the program jumps to the except block and prints an error message indicating that the conversion to an integer failed.

Question 11

Consider the code given below and fill in the blanks with appropriate error types:

loop = 1
while loop == 1:
      try:
         a = int(input('Enter the first number: ')
         b = int(input('Enter the second number: ')
         quotient = a/b
      except ...............:
         print("Error: Please enter only numbers")
      except ...............:
         print("\n Error: Second number should not be zero")
      except ...............:
         print("\n Unsupported operation: Check the date type")
      else:
         print("Great")
      finally:
         print("Program execution completed")
loop = int(input('Press 1 to try again !')
continue

Answer

loop = 1
while loop == 1:
    try:
        a = int(input('Enter the first number: '))
        b = int(input('Enter the second number: '))
        quotient = a / b
    except ValueError:
        print("Error: Please enter only numbers")
    except ZeroDivisionError:
        print("\n Error: Second number should not be zero")
    except TypeError:
        print("\n Unsupported operation: Check the data type")
    else:
        print("Great")
    finally:
        print("Program execution completed")
loop = int(input('Press 1 to try again: '))
continue

In the code:

  1. The ValueError exception is used to catch errors that occur when the input cannot be converted to an integer (e.g., if the user enters a non-numeric value).
  2. The ZeroDivisionError exception is used to catch errors that occur when attempting to divide by zero (i.e., when the second number is zero).
  3. The TypeError exception is used to catch errors related to unsupported operations, such as performing arithmetic operations on incompatible data types.
PrevNext