Exception Handling in Python - Class 12 Computer Science - Chapter 1 - Notes, NCERT Solutions & Extra Questions
Renews every month. Cancel anytime
Your personal doubt-solving assistant
Chatterbot AI gives you 100% accurate answers to your questions in an instant.
Notes - Exception Handling in Python | Class 12 NCERT | Computer Science
Exception Handling in Python: Class 12 Notes
Introduction
Exception handling is a crucial aspect of Python programming, enabling developers to manage and resolve errors that occur during the execution of a program. It ensures that the code runs smoothly, even when unexpected conditions arise, thereby preventing abrupt terminations and maintaining user experience.
Syntax Errors
Syntax errors, also known as parsing errors, occur when the rules of the programming language are not followed. These errors are detected by the Python interpreter during the parsing phase and must be rectified before the program can be executed. For instance:
if marks > 20:
print "GOOD SCORE"
Fixed Syntax
if marks > 20:
print("GOOD SCORE")
Here, the first snippet will cause a syntax error due to the missing parentheses in the print
function.
Exceptions
Unlike syntax errors, exceptions occur during the actual execution of the program. They are runtime errors that can disrupt the normal flow of the program. Common examples include opening a non-existent file or division by zero. These errors need to be handled to prevent abnormal program termination.
What is the primary purpose of exception handling in Python?
Built-in Exceptions
Python's standard library comes with a collection of built-in exceptions that cover common errors. Some of these include:
Exception | Description |
---|---|
SyntaxError | Raised when there is a syntax error in the code. |
ValueError | Raised when a function receives an argument of the correct type but inappropriate value. |
IOError | Raised when an I/O operation fails. |
ZeroDivisionError | Raised when attempting to divide by zero. |
IndexError | Raised when an index is out of range. |
TypeError | Raised when an operation is applied to an object of inappropriate type. |
Raising Exceptions
Python allows programmers to raise exceptions intentionally using the raise
statement. This is useful for testing error-handling routines or when a specific condition must be met for the program to proceed.
raise Exception("This is a raised exception")
Handling Exceptions
Try and Except Blocks
The primary way to handle exceptions in Python is using try
and except
blocks. The code that might throw an exception is placed inside the try
block, and the corresponding handling code is in the except
block.
try:
numerator = 10
denominator = 0
result = numerator / denominator
except ZeroDivisionError:
print("Division by zero is not allowed")
The Finally Clause
The finally
block contains code that will execute regardless of whether an exception was raised or not. This is commonly used for cleanup actions, such as closing files or releasing resources.
try:
file = open("test.txt", "r")
except FileNotFoundError:
print("File not found")
finally:
file.close()
print("File has been closed")
The Assert Statement
The assert
statement is used to test, if a condition in the code returns True, otherwise it raises an AssertionError. It's a convenient way to insert debugging assertions into a program.
def check_age(age):
assert age >= 0, "Age cannot be negative"
return age
print(check_age(25))
What will happen if a ZeroDivisionError exception occurs in a try block that does not have a matching except block?
The Process of Handling Exceptions
When an error occurs, Python creates an exception object. This object is then handled by the runtime system, which looks for a matching except
block to catch and handle the error.
flowchart TD
A[Start Program] --> B[Try Block]
B -->|Exception Occurs| C[Except Block]
B -->|No Exception| D[Else Block]
B -->|Finally Block| E
C -->|Handled| E
D --> E[Continue Execution]
E -->|Finally Executes| F[End Program]
User-defined Exceptions
Python also allows the creation of custom exceptions tailored to specific needs using class definitions.
class CustomError(Exception):
pass
try:
raise CustomError("This is a custom error")
except CustomError as e:
print(e)
Best Practices for Exception Handling
Catch Specific Exceptions: Avoid using a bare
except
clause; instead, catch specific exceptions to prevent catching unexpected errors.Use Finally for Cleanup: Ensure resources are released whether an error occurs or not by using the
finally
block.Document Your Code: Clearly document why and how exceptions are being handled for better code maintainability.
Which block in exception handling will always execute, whether an exception is raised or not?
Conclusion
Understanding and implementing exception handling is essential for writing robust and error-free Python programs. By learning these techniques, you can ensure your programs are well-prepared to handle unexpected situations gracefully.
🚀 Learn more about Notes with Chatterbot AI
NCERT Solutions - Exception Handling in Python | NCERT | Computer Science | Class 12
"Every syntax error is an exception but every exception cannot be a syntax error." Justify the statement.
The statement "Every syntax error is an exception but every exception cannot be a syntax together" is justified as follows:
Syntax errors are exceptions: In Python, syntax errors occur when the code does not conform to the syntax rules of the language. For instance, forgetting a parenthesis or mismatching indentation can trigger a SyntaxError. These are subclassed under exceptions, and the Python interpreter flags these errors before the code is executed. Therefore, every syntax error is indeed an exception, specifically a subclass of an exception that deals with syntactical faults in code.
Not all exceptions are syntax errors: Exceptions in Python handle a broader range of issues beyond just syntax-related errors. Exceptions can occur during the execution of a program at runtime, handling issues such as operations that the code is unable to perform (like division by zero), or environmental issues (like reading a non-existent file). These are known as runtime exceptions and include ZeroDivisionError, FileNotFoundError, etc., which are not related to syntax but to the logic, state of resources, or conditions during the execution of the program.
Thus, while syntax errors strictly relate to incorrect Python syntax preventing the code from running, exceptions can be raised due to various errors that might occur during runtime as well as compile time (syntax error being one such compile-time exception). This distinction supports the given statement effectively.
When are the following built-in exceptions raised? Give examples to support your answers.
a) ImportError
b) IOError
c) NameError
d) ZeroDivisionError
Built-in Exceptions and Their Scenarios
a) ImportError
Raised when: An ImportError
is raised when Python cannot find the module or the specific symbol within a module you are trying to import.
Example:
try:
import non_existent_module
except ImportError as e:
print(e)
b) IOError
(Note: In Python 3.x, it is known as OSError
)
Raised when: An IOError
was commonly raised when an input/output operation fails, such as failing to open a file that does not exist. In Python 3.x, these kinds of issues are typically raised as OSError
or more specific exceptions like FileNotFoundError
.
Example:
try:
with open('non_existent_file.txt') as f:
content = f.read()
except IOError as e: # Use FileNotFoundError in Python 3.x
print(e)
c) NameError
Raised when: A NameError
is thrown when a variable or function name is not defined in the local or global scope.
Example:
try:
print(undefined_variable)
except NameError as e:
print(e)
d) ZeroDivisionError
Raised when: A ZeroDivisionError
is raised when a division or modulo operation is attempted with zero as the divisor.
Example:
try:
result = 10 / 0
except ZeroDivisionError as e:
print(e)
These examples illustrate how each exception can be triggered by specific errors in a Python script.
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 in Python is used to trigger an exception manually. This is particularly useful when you want to enforce certain conditions within your code and handle errors or exceptional situations that occur.
Here's a Python code that accepts two numbers and displays the quotient. If the user enters the second number (denominator) as zero, it raises a ZeroDivisionError
.
Python Code:
# Function to compute the quotient of two numbers
def compute_quotient(first_number, second_number):
# Check if the denominator is zero
if second_number == 0:
raise ZeroDivisionError("Denominator cannot be zero.")
return first_number / second_number
# Input from user
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))
# Compute and display the quotient
try:
quotient = compute_quotient(numerator, denominator)
print("The quotient is:", quotient)
except ZeroDivisionError as e:
print(e)
Explanation:
The function
compute_quotient
checks if the denominator is zero. If it is, it raises aZeroDivisionError
with a message saying "Denominator cannot be zero."In the main part of the code, the numerator and denominator are taken as inputs from the user.
The
try
block is used to attempt the division, and if theZeroDivisionError
is raised, it is caught by theexcept
block, which then prints the error message.
Use assert statement in Question No. 3 to test the division expression in the program.
The raise
statement is used in Python to forcefully trigger an exception when a specific condition arises. This enables the programmer to create customized error handling pathways in their code, making it more robust by checking for unusual or invalid conditions.
The assert
statement is used to test a condition, and if the condition is False
, an AssertionError
exception is raised. This can be employed to check for validity of the input or the results during the runtime of the program.
Here's an example Python code that accepts two numbers from the user for division, displays the quotient, and appropriately handles the situation when the denominator is zero using raise
. Additionally, it uses the assert
statement to verify that the division expression is valid.
def divide_numbers():
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))
# Check if the denominator is zero and raise an exception if true
if denominator == 0:
raise ValueError("Denominator cannot be zero.")
# Using assert to ensure the denominator is not zero
assert denominator != 0, "Denominator is zero during assertion check."
quotient = numerator / denominator
return quotient
try:
result = divide_numbers()
print("The result of the division is:", result)
except ValueError as e:
# Handle the raised exception
print(e)
except AssertionError as e:
# Handle any assertion errors
print(e)
The above program works as follows:
It prompts the user to enter the numerator and denominator.
It checks if the denominator is zero using an
if
statement. If yes, it raises aValueError
.An
assert
statement is also used to double-check that the denominator is not zero.If the input is valid, it calculates and prints the quotient.
Errors (
ValueError
fromraise
andAssertionError
fromassert
) are caught and handled in the try-except block.
Define the following:
a) Exception Handling
b) Throwing an exception
c) Catching an exception
a) Exception Handling
Exception handling refers to the process of responding to the occurrence of exceptions – anomalous or exceptional conditions requiring special processing – during the execution of a program. In Python, this is typically accomplished using try
, except
, else
, and finally
blocks. This technique helps in preventing the program from crashing by providing a way to handle errors gracefully, ensuring that the flow of the application can continue or terminate cleanly.
b) Throwing an Exception
Throwing an exception refers to the act of raising an exception when an error or unusual condition is encountered. In Python, exceptions can be thrown using statements like raise
and assert
. The process interrupts the normal flow of program execution and passes the error handling responsibility to the surrounding context or the runtime environment.
c) Catching an Exception
Catching an exception is the method by which an exception that has been thrown is then handled with specific actions or logging. This is done in the except
block of a try
...except
statement. The exception is 'caught', and specific code is executed to either recover from the error, provide a user-friendly error message, or otherwise respond to the fact that the exception occurred. This allows the program to continue running or to fail gracefully instead of crashing unexpectedly.
Explain catching exceptions using try and except block.
Catching exceptions in Python involves the use of a try
block followed by one or more except
blocks. This structure allows the program to handle errors gracefully without crashing. Here’s how it works:
1. Try Block
You place code that might cause an exception within the
try
block. Python attempts to execute this code as normal.
2. Except Block(s)
Following the
try
block, you include one or moreexcept
blocks. These blocks catch and handle exceptions if they occur within thetry
block.Each `info:From Section 1:
option>block is set up to handle a specific exception type. You can have multiple
except` blocks to handle different exceptions differently.
Syntax:
try:
# Code that might throw an exception
except <ExceptionType>:
# Code that runs if an exception of <ExceptionType> occurs
except another_exception_type:
# Code to handle another type of exception
else:
# Code that runs if no exceptions occur
finally:
# Code that runs no matter what happens
Example:
try:
numerator = 10
denom = int(input("Enter the denominator: "))
result = numerator / denom
except ValueError:
print("Please enter a valid integer.")
except ZeroDivisionError:
print("Division by zero is not allowed.")
except:
print("An unexpected error occurred.")
else:
print("The result is", result)
finally:
print("This always executes.")
Execution Flow:
If No Exception: Code in
try
runs. If no exceptions,else
(if present) runs aftertry
.If Exception Occurs: The remainder of the
try
block is skipped. Python looks for anexcept
block matching the exception type and executes it.Finally: Whether an exception occurred or not, and after exception handling, the
finally
block executes.
Using try
and except
blocks helps to make programs more robust and user-friendly by gracefully handling errors instead of crashing unexpectedly.
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")
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")
The first except
block catches a type error known as ValueError
to handle cases where the user input is not a valid integer. The second except
block captures ZeroDivisionError
, which occurs when attempting to divide by zero. The final block, marked by finally
, ensures that a specific set of statements will be executed irrespective of whether or not an exception was caught.
You have learnt how to use math module in Class XI. Write a code where you use the wrong number of arguments for a method (say sqrt()
or pow()
). Use the exception handling process to catch the ValueError
exception.
Below is an example of Python code that demonstrates how to handle a TypeError
(not ValueError
as ValueError
is typically raised for issues with the content of the data rather than issues related to incorrect number or type of arguments) when the wrong number of arguments are passed to the sqrt
method from the math
module:
import math
try:
# Incorrect usage of sqrt by passing two arguments instead of one
result = math.sqrt(9, 4)
except TypeError as e:
print("Error:", e)
Here, the code tries to use the math.sqrt()
function with two arguments, which is incorrect as math.sqrt()
requires exactly one argument. Since this misuse matches the TypeError
, the error message generated by this misuse will be caught and printed.
Note: If you need to handle Value error
, it would typically occur when an inappropriate value (e.g., negative number for math.sqrt()
) is passed, not due to wrong number of arguments.
What is the use of finally clause? Use finally clause in the problem given in Question No. 7.
The finally
clause in Python is used to specify a block of code that will be executed, regardless of whether an exception occurs or not within the try
block. It typically contains clean-up actions that must be executed under all circumstances, such as releasing resources (like closing a file).
In the provided problem, you can integrate the finally
clause to ensure that a particular message is displayed, marking the end of the procedure, no matter the outcome of the try-except-else
structure.
Here is the updated code:
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")
ValueError
handles cases where the conversion of input to an integer fails.ZeroDivisionError
catches scenarios where division by zero occurs.finally
ensures that "JOB OVER... GO GET SOME REST" is printed whether an error occurs or not.
💡 Have more questions?
Ask Chatterbot AI