What is exceptions? Discuss how exceptions simplify programs.
ANS: In Python, an exception is an event that occurs during the execution of a program, disrupting the normal flow of instructions. Exceptions are often raised when an error occurs, such as a division by zero, file not found, or an invalid input.
How exceptions simplify programs:
Separation of Error Handling:
Exceptions allow you to separate the error-handling code from the main logic of your program. This makes your code more readable, maintainable, and easier to understand.
Graceful Handling of Errors:
Without exceptions, you would need to manually check for potential errors at every step of your program. This can be tedious and error-prone. Exceptions provide a structured way to handle errors, ensuring that your program doesn't crash unexpectedly.
Specific Error Handling:
You can catch specific types of exceptions and handle them differently. This allows you to provide more tailored error messages and take appropriate actions depending on the nature of the error.
Propagation of Errors:
Exceptions can be propagated up the call stack, allowing higher-level functions to handle them. This means that you don't need to handle every possible error in every function.
Built-in Exception Hierarchy:
Python provides a rich hierarchy of built-in exceptions, making it easy to identify and handle different types of errors.
Example:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
What do you mean by Assertion ? Explain with example.
ANS:
Assertions in Python:
In Python, an assertion is a statement that declares a condition that should always be true during program execution. It's essentially a debugging tool that helps you catch errors early in the development process.
Syntax:
assert condition, error_message
How it works:
Condition Check: The condition is evaluated.
True: If the condition is True, the program continues to the next line.
False: If the condition is False, an AssertionError is raised, along with the optional error_message.
Example:
def divide(a, b):
assert b != 0, "Division by zero error"
return a / b
result = divide(10, 2) # This will work
print(result)
result2 = divide(10, 0) # This will raise an AssertionError
print(result2)
What is exception? Explain how to handle user defined exception in python (Give example)?
ANS: In Python, an exception is an event that occurs during the execution of a program that disrupts the normal flow of control. When an exception occurs, the Python interpreter raises an exception object, and if not handled properly, the program terminates abruptly.
Handling Exceptions
To handle exceptions, we use a try-except block.
Syntax:
try:
# Code that might raise an exception
except ExceptionType:
# Code to handle the exception
Example:
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("Error: Division by zero")
else:
print("Result:", result)
finally:
print("This block always executes")
divide(10, 2) # Output: Result: 5.0
divide(10, 0) # Output: Error: Division by zero
User-Defined Exceptions
You can define your own custom exceptions by creating a new class that inherits from the built-in Exception class.
Example:
class NegativeNumberError(Exception):
pass
def factorial(n):
if n < 0:
raise NegativeNumberError("Factorial is not defined for negative numbers")
elif n == 0:
return 1
else:
return n * factorial(n - 1)
try:
print(factorial(-5))
except NegativeNumberError as e:
print(e)
Say TRUE of FALSE with justification.
a) While doing exception handling, “else” is the block which executes in all the situations
whether exception occurs or not.
b) There is nothing rare about exceptions in Python
c) While doing exception handling, “else” is the block which executes in all the situations
whether exception occurs or not.
ANS:
a) FALSE. The else block in a try-except block only executes when no exceptions are raised within the try block.
b) FALSE. While exceptions are common in Python and other programming languages, they should be handled gracefully to prevent program crashes. Well-written code should minimize the likelihood of exceptions occurring.
c) FALSE. As explained in (a), the else block only executes when no exceptions are raised within the try block.
Discuss use of assert statement.
ANS: The assert statement in Python is a powerful tool for debugging and testing code. It's used to verify assumptions and conditions within your code.
How it works:
Condition Check: The assert statement evaluates a specified condition.
True: If the condition is True, the program continues to the next line.
False: If the condition is False, an AssertionError is raised, along with an optional error message.
Syntax:
assert condition, error_message
Common Use Cases:
Debugging:
Early Error Detection: Identify errors early in development.
Assumption Verification: Ensure that assumptions about your code's behavior are correct.
Invariant Checking: Verify conditions that should always hold true.
Testing:
Unit Tests: Use assert to check the correctness of specific functions or methods.
Integration Tests: Verify the interaction between different parts of your code.
Example:
def divide(a, b):
assert b != 0, "Division by zero error"
return a / b
result = divide(10, 2) # This will work
print(result)
result2 = divide(10, 0) # This will raise an AssertionError
print(result2)
What is Exception? Explain exception handling with example.
ANS: An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. In simpler terms, it's an error that happens while your program is running.
Exception Handling
Exception handling is a mechanism to deal with these exceptions gracefully, preventing your program from crashing and providing a more robust and user-friendly experience.
Example:
def divide(x, y):
try:
result = x / y
print("Result:", result)
except ZeroDivisionError:
print("Error: Division by zero")
divide(10, 0)
Explanation:
try block: This block contains the code that might throw an exception. Here, we're trying to divide x by y.
except block: This block specifies the type of exception we want to handle. In this case, we're handling the ZeroDivisionError exception, which occurs when you try to divide a number by zero. If this exception occurs, the code inside the except block will be executed.
Write exception block in python. How to use exception as a control flow mechanism?
ANS: In Python, exception blocks are defined using the try and except keywords. The try block contains the code that might raise an exception, while the except block handles the exception if it occurs.
Basic Example:
try:
# Code that might raise an exception
x = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero")
Multiple except Blocks:
You can have multiple except blocks to handle different types of exceptions:
try:
# Code that might raise an exception
x = int(input("Enter a number: "))
y = 10 / x
except ZeroDivisionError:
print("Error: Division by zero")
except ValueError:
print("Error: Invalid input")
General Exception Handling:
You can use a generic except block to catch any exception that isn't specifically handled:
try:
# Code that might raise an exception
x = int(input("Enter a number: "))
y = 10 / x
except Exception as e:
print("An error occurred:", e)
Using Exceptions as a Control Flow Mechanism
While exceptions are primarily used for error handling, they can also be used as a control flow mechanism in certain scenarios. This is often not recommended as it can make code less readable and maintainable. However, in some specific cases, it can be useful:
Early Termination: You can raise an exception to immediately terminate a function or loop:
def process_data(data):
for item in data:
if item < 0:
raise ValueError("Negative value encountered")
# Process the item
Signaling Abnormal Conditions: You can raise a custom exception to signal an abnormal condition:
class DataValidationError(Exception):
pass
def validate_data(data):
if not data:
raise DataValidationError("Data is empty")
# Validate other conditions
Discuss the use of raise statement with example.
ANS: The raise statement in Python is used to explicitly raise an exception. This can be useful in various scenarios, such as:
Signaling Errors: When a function encounters an error condition that it cannot handle, it can raise an appropriate exception to inform the caller.
def divide(x, y):
if y == 0:
raise ZeroDivisionError("Division by zero")
return x / y
Custom Exceptions: You can define your own custom exceptions to represent specific error conditions:
class NegativeValueError(Exception):
pass def calculate_sqrt(x):
if x < 0:
raise NegativeValueError("Cannot calculate square root of negative number") return x**0.5
Re-raising Exceptions: You can re-raise an exception to propagate it to a higher level of the call stack:
def process_data(data):
try:
# Process the data ... except ValueError as e:
print("Error processing data:", e) raise
# Re-raise the exception
Explain logging in python with proper example.
ANS: Logging is a powerful technique to record events, errors, and other information during the execution of a Python program. It helps in debugging, monitoring, and analyzing the behavior of your application.
The logging Module
Python's built-in logging module provides a flexible framework for logging. Here's a basic example:
import logging
# Create a logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# Create a formatter
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
# Create a console handler
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
# Add the handler to the logger
logger.addHandler(console_handler)
# Log messages
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
logger.critical('This is a critical message')
Explanation:
Logger Creation:
getLogger(__name__): Creates a logger instance with the name of the current module.
setLevel(logging.DEBUG): Sets the minimum severity level for log messages.
Formatter Creation:
logging.Formatter(): Creates a formatter object to specify the format of log messages.
Handler Creation:
logging.StreamHandler(): Creates a handler to log messages to the console.
Handler Configuration:
setFormatter(): Associates the formatter with the handler.
Handler Addition:
addHandler(): Adds the handler to the logger.
Logging Messages:
logger.debug(), logger.info(), logger.warning(), logger.error(), and logger.critical(): Log messages with different severity levels.
Write a Python program which reads a number from user repeatedly and if number is not in range of values a, b, where a<b , it raises custom exception tooBigNumber and tooSmallNumber.
when user enters number in range, it prints "Valid Number" and terminates.
ANS:
class TooBigNumber(Exception):
pass
class TooSmallNumber(Exception):
pass
def read_number(a, b):
while True:
try:
num = int(input("Enter a number: "))
if num < a:
raise TooSmallNumber("Number is too small")
elif num > b:
raise TooBigNumber("Number is too big")
else:
print("Valid Number")
break
except TooSmallNumber as e:
print(e)
except TooBigNumber as e:
print(e)
# Example usage:
a = 10
b = 20
read_number(a, b)
Explanation:
Custom Exceptions:
We define two custom exceptions, TooBigNumber and TooSmallNumber, to represent the specific error conditions.
read_number Function:
Takes two arguments, a and b, representing the range limits.
Inside a while True loop, it repeatedly prompts the user for a number.
Converts the input to an integer using int().
Checks if the number is within the range:
If it's too small, raises a TooSmallNumber exception.
If it's too big, raises a TooBigNumber exception.
If it's within the range, prints "Valid Number" and breaks the loop.
The try-except block handles the custom exceptions and prints appropriate error messages.
List out keywords used in exception handling and explain with example. Write a Python program which will throw exception if the value entered by user is less than zero.
ANS: Keywords Used in Exception Handling in Python:
try:
Encloses a block of code that might raise an exception.
If no exception occurs, the except block is skipped.
try:
x = int(input("Enter a number: "))
except ValueError:
print("Invalid input")
except:
Defines a block of code to be executed if a specific exception occurs.
Can handle multiple exceptions using multiple except blocks.
try:
x = 10 / 0 except ZeroDivisionError:
print("Division by zero error")
finally:
Defines a block of code to be executed regardless of whether an exception occurs or not.
Often used for cleanup operations, like closing files or releasing resources.
try:
f = open("myfile.txt", "r")
# ... finally:
f.close()
raise:
Raises an exception explicitly.
Can be used to create custom exceptions or re-raise exceptions.
def divide(x, y):
if y == 0:
raise ZeroDivisionError("Division by zero")
return x / y
Python Program to Handle Negative Input:
class NegativeValueError(Exception):
pass
def get_positive_number():
while True:
try:
num = int(input("Enter a positive number: "))
if num < 0:
raise NegativeValueError("Number cannot be negative")
return num
except ValueError:
print("Invalid input. Please enter a number.")
except NegativeValueError as e:
print(e)
# Example usage:
positive_number = get_positive_number()
print("You entered:", positive_number)
Explanation:
Custom Exception:
We define a custom exception NegativeValueError to specifically handle negative input.
get_positive_number Function:
A while True loop is used to repeatedly prompt the user for input.
The input is converted to an integer using int().
If the number is negative, a NegativeValueError is raised.
If the input is invalid (not a number), a ValueError is raised.
The try-except block handles both custom and built-in exceptions.
If the input is valid and positive, the function returns the number.
Nice Work