We handle errors or exceptions in a program through exception handling in Python. When an error occurs during the execution of a program, exceptions are raised in Python. Exception handling enables us to handle these errors and prevent the program from crashing. We use the try
and except
statements for exception handling in Python. The try
block holds the code that can raise an exception, and the corresponding except
block holds the code to handle the exception.
1. “Every syntax error is an exception but every exception cannot be a syntax error.” Justify the statement.
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.
- ImportError
- IOError
- NameError
- ZeroDivisionError
a) 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:
1 | 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 try
–except
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:
1 2 3 4 5 | 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
:
1 2 3 4 | >>> 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
:
1 2 3 4 | >>> 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:
1 2 3 | >>> x = 5 >>> y = 0 >>> print(x/y) |
This exception can be handled using a try
–except
block to provide a more meaningful error message or to handle the error in a different way. For example:
1 2 3 4 | 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):
1 2 3 4 5 6 7 8 | 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.
1 2 3 4 5 6 7 8 | 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:
- Exception Handling
- Throwing an exception
- 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:
1 2 3 4 | 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:
1 2 3 4 5 6 7 | 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:
1 2 3 4 5 | 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 try
–except
block to handle it appropriately.
1 2 3 4 | try: positive_number(-5) except ValueError as e: print("Error:", e) |
This code will output:
1 | 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 try
–except
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.
1 2 3 4 5 6 7 8 9 10 | 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:
1 2 3 4 5 6 7 8 9 10 11 12 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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") |
8. 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.
Here’s an example of using exception handling to catch the ValueError that is raised when the wrong number of arguments are used for the math.sqrt() method:
1 2 3 4 5 6 7 8 9 10 11 12 | import math try: x = float(input("Enter a number to find its square root: ")) result = math.sqrt(x, 2) # providing two arguments instead of one except ValueError as ve: print("Error: Invalid argument for sqrt() method.") print("Message:", str(ve)) except Exception as e: print("An error occurred:", str(e)) else: print("Square root of", x, "is", result) |
In this code, the user is prompted to enter a number. The square root of the entered number is calculated using the math.sqrt()
method. Since we have provided two arguments instead of one, a ValueError
exception is raised. The except
block catches the ValueError
exception, prints an error message, and continues with the next line of code. If no exception is raised, the code inside the else
block is executed.
9. 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 no matter what. The finally
clause is placed after the except
clause(s) in a try
statement.
The purpose of the finally clause is to ensure that some code is executed regardless of whether an exception was raised or not. For example, you might use the finally
clause to close a file that was opened in the try
block, or to release a resource that was acquired.
Use finally clause in the problem given in Question No. 7.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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") |