Exception Handling Notes and Solved Question and Answers

                                                              Exception Handling

Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are problems in a program due to which will stop the program from execution. On the other hand, exceptions are raised when some internal events occur due to limitation of hardware or software part, which change the normal flow of the program.

Different types of exceptions in python:

 • SyntaxError: This exception is raised when the interpreter encounters a syntax error in the code, such as a misspelled keyword, a missing colon, or an unbalanced parenthesis.

 • TypeError: This exception is raised when an operation or function is applied to an object of the wrong type, such as adding a string to an integer. 

• NameError: This exception is raised when a variable or function name is not found in the current scope.

 • IndexError: This exception is raised when an index is out of range for a list, tuple, or other sequence types. 

• KeyError: This exception is raised when a key is not found in a dictionary.

 • ValueError: This exception is raised when a function or method is called with an invalid argument or input, such as trying to convert a string to an integer when the string does not represent a valid integer.

 • AttributeError: This exception is raised when an attribute or method is not found on an object, such as trying to access a non-existent attribute of a class instance. 

• IOError: This exception is raised when an I/O operation, such as reading or writing a file, fails due to an input/output error.

 • ZeroDivisionError: This exception is raised when an attempt is made to divide a number by zero.

 • ImportError: This exception is raised when an import statement fails to find or load a module

Difference between Syntax Error and Exceptions 

Syntax Error: This error is caused by the wrong syntax in the code.

if(amount > 999)

 print(“amount more than 1000") 

if(amount > 999)

Syntax error Invalid Syntax

Exceptions: Exceptions are raised when the program is syntactically correct, but the code results in an error. This error does not stop the execution of the program, however, it changes the normal flow of the program.

 a = 10 / 0 

print(a)

Zero Division Error: Division by zero

handling exceptions using try-except finally blocks 

try: 

# Some Code....which may have runtime error 

except:

 # optional block

 # Handling of exception (if required)

 else: 

# execute if no exception finally: 

# Some code .....(always executed)

try:

 k = 9//0 # raises divide by zero exception. 

print(k)

# handles zerodivision exception 

except ZeroDivisionError: 

print("Can't divide by zero")

finally:

# this block is always executed

# regardless of exception generation.

print('This is always executed')

Advantages of Exception Handling: 

• Improved program reliability 

• Simplified error handling 

• Cleaner code 

• Easier debugging 

Disadvantages of Exception Handling:

 • Performance overhead 

• Increased code complexity

 • Possible security risks  

Practice Questions and Answers

1. “Every syntax error is an exception but every exception cannot be a syntax error.” Justify the statement.
Ans) This statement means that not all exceptions in Python are syntax errors, but all syntax errors are exceptions.

A syntax error is a type of exception that occurs when the Python interpreter encounters invalid syntax in the code, such as a missing parenthesis or incorrect indentation. These errors prevent the code from executing because the interpreter cannot understand the code as it is written.

However, there are other types of exceptions in Python that are not related to syntax errors. For example, an exception can be raised when a program tries to divide by zero, or when a program tries to access a list index that is out of range. These exceptions occur during the execution of the program and are not related to the syntax of the code.

Therefore, the statement “Every syntax error is an exception but every exception cannot be a syntax error” is true because all syntax errors are exceptions, but not all exceptions are syntax errors.

2.When are the following built-in exceptions raised? Give examples to support your answers.

  1. ImportError
  2. IOError
  3. NameError
  4. ZeroDivisionError

When the ImportError built-in exceptions raised in Python?

The ImportError built-in exception is raised in Python when an imported module or its dependencies are not found. This exception is raised when the Python interpreter cannot find the module specified in an import statement or when the module or its dependencies raise an import error.

For example, the following code raises an ImportError if the module example_module is not found in the current environment:

a)import example_module

This exception is typically raised when a required module or its dependencies are not installed or not accessible in the current environment. To handle this exception, you can wrap the import statement in a tryexcept block and provide a proper error message or alternative code to execute when the exception is raised.

b) When the IOError built-in exceptions raised in Python?

The IOError built-in exception is raised in Python when there is an input/output error, such as an error reading or writing a file. For example, an IOError may be raised if a file that a program is trying to read does not exist or if the program does not have permission to access the file. It can also be raised if a program tries to write to a file that it does not have permission to modify, or if there is an issue with the storage device where the file is stored.

Here is an example of how the IOError exception can be raised in Python:

try:

with open("file.txt") as f:

data = f.read()

except IOError:

print("An error occurred while trying to read the file.")

c) When the NameError built-in exceptions raised in Python?

The NameError built-in exception is raised in Python when a name (variable, function, class, etc.) is not found in the current namespace. This usually means that the name has not been defined or has been misspelled.

For example, if you try to use a variable that has not been defined, you will get a NameError:

>>> print(x)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name 'x' is not defined

Similarly, if you try to call a function that has not been defined, you will also get a NameError:

>>> my_function()

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name 'my_function' is not defined

d) When the ZeroDivisionError built-in exceptions raised in Python?

The ZeroDivisionError built-in exception is raised in Python when a program tries to divide a number by zero. For example:

>>> x = 5

>>> y = 0

>>> print(x/y)

This exception can be handled using a tryexcept block to provide a more meaningful error message or to handle the error in a different way. For example:

try:

result = 5 / 0

except ZeroDivisionError:

print("Cannot divide by zero.")

The ZeroDivisionError exception indicates that an attempt was made to divide by zero, which is undefined in mathematics. In Python, this exception is raised to prevent incorrect results and indicate that there is a problem with the code. To handle this exception, you can use a try and except block in your code to catch the exception and handle it appropriately.

3. What is the use of a raise statement? Write a code to accept two numbers and display the quotient. Appropriate exception should be raised if the user enters the second number (denominator) as zero (0).

The raise statement is used to raise an exception explicitly in Python. It can be used to handle specific cases and provide custom error messages.

Here’s a code that accepts two numbers as input and displays their quotient. An appropriate exception is raised if the user enters the second number (denominator) as zero (0):

num1 = float(input("Enter the first number: "))

num2 = float(input("Enter the second number: "))


if num2 == 0:

    raise Exception("The denominator cannot be zero")

else:

    quotient = num1 / num2

    print("The quotient of", num1, "and", num2, "is", quotient)

4. Use assert statement in Question No. 3 to test the division expression in the program.

num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

if num2 == 0:
    raise Exception("The denominator cannot be zero")
else:
    quotient = num1 / num2
    print("The quotient of", num1, "and", num2, "is", quotient)

5. Define the following:

  1. Exception Handling
  2. Throwing an exception
  3. Catching an exception

Exception Handling

Exception handling in Python allows you to handle errors and exceptions that occur during the execution of a program. It helps to prevent the program from crashing and allows you to provide a custom error message or take other actions to handle the error.

The basic structure of exception handling in Python is as follows:

try:

    # code that may raise an exception

except ExceptionType:

    # code to handle the exception

Here’s an example of how you can use exception handling to handle a ZeroDivisionError that occurs when dividing a number by zero:

try:

    num1 = float(input("Enter the first number: "))

    num2 = float(input("Enter the second number: "))

    quotient = num1 / num2

    print("The quotient of", num1, "and", num2, "is", quotient)

except ZeroDivisionError:

    print("Cannot divide by zero.")

In this example, the code in the try block prompts the user for two numbers and calculates their quotient. If the user enters a value of 0 for the second number (denominator), a ZeroDivisionError will be raised. The code in the except block handles this error by printing a message “Cannot divide by zero.” The program continues executing after the error is handled.

Throwing an exception

Throwing an exception in Python means raising an exception explicitly in the code to signal an error or an abnormal situation. The raise statement is used to throw an exception in Python.For example, consider a function that accepts a value and raises an exception if the value is negative:

def positive_number(value):

    if value < 0:

        raise ValueError("Value must be positive.")

    else:

        print("Value is positive.")

In this example, if the value passed to the positive_number function is negative, the raise statement raises a ValueError exception with the message “Value must be positive.”. The caller of the function can catch the exception using a tryexcept block to handle it appropriately.

try:

    positive_number(-5)

except ValueError as e:

    print("Error:", e)

This code will output:

Error: Value must be positive.

Catching an exception

Catching an exception in Python means handling an exception that is raised during the execution of a program. This is done using a tryexcept block. The code that might raise an exception is placed in the try block, and the code to handle the exception is placed in the corresponding except block.

try:

    num1 = float(input("Enter the first number: "))

    num2 = float(input("Enter the second number: "))

    result = num1 / num2

except ZeroDivisionError:

    print("Cannot divide by zero.")

except ValueError:

    print("Invalid input. Only numbers are allowed.")

else:

    print("The result is", result)

In this example, the program accepts two numbers as input from the user and divides the first number by the second number. If the second number is zero, a ZeroDivisionError is raised and caught in the except block, and the message “Cannot divide by zero” is displayed. If the user inputs something other than a number, a ValueError is raised and caught in the corresponding except block, and the message “Invalid input. Only numbers are allowed.” is displayed. If no exceptions are raised, the result of the division is printed.

6. Explain catching exceptions using try and except block

The try and except blocks are used in Python to handle exceptions, or runtime errors. The code that may raise an exception is placed inside a try block. If an exception occurs, the code inside the except block is executed. The except block provides an opportunity to handle the exception gracefully, rather than letting the program crash.

Here’s an example of how you can use the try and except blocks:

try:

    # some code that may raise an exception

    result = int("a")

except ValueError as ve:

    # code to handle the exception

    print("Error: Could not convert string to integer.")

except Exception as e:

    # generic exception handler

    print("An error occurred:", str(e))

else:

    # code to be executed if there is no exception

    print("Result:", result)

In this example, the code inside the try block tries to convert a string to an integer. Since the string is not a valid integer, a ValueError exception is raised. The except block handles the ValueError exception and prints an error message. If no exception is raised, the code inside the else block is executed.

7. Consider the code given below and fill in the blanks

print (" Learning Exceptions...")
try:
 num1= int(input ("Enter the first number"))
 num2=int(input("Enter the second number"))
 quotient=(num1/num2)
 print ("Both the numbers entered were correct")
except _____________: # to enter only integers
 print (" Please enter only numbers")
except ____________: # Denominator should not be zero
 print(" Number 2 should not be zero")
else:
 print(" Great .. you are a good programmer")
___________: # to be executed at the end
 print(" JOB OVER... GO GET SOME REST")
Answer:

print (" Learning Exceptions...")
try:
 num1= int(input ("Enter the first number"))
 num2=int(input("Enter the second number"))
 quotient=(num1/num2)
 print ("Both the numbers entered were correct")
except ValueError: # to enter only integers
 print (" Please enter only numbers")
except ZeroDivisionError: # Denominator should not be zero
 print(" Number 2 should not be zero")
else:
 print(" Great .. you are a good programmer")
finally: # to be executed at the end
 print(" JOB OVER... GO GET SOME REST")



Comments

Popular posts from this blog

Class XII CSC Question Paper Template for 2023-24

DATA FILE HANDLING