KEMBAR78
Exception Handling | PDF | Computer File | Computer Program
0% found this document useful (0 votes)
5 views14 pages

Exception Handling

Uploaded by

titeer123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views14 pages

Exception Handling

Uploaded by

titeer123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

1. “Every syntax error is an exception but every exception cannot be a syntax error.

” Justify
the statement.

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.
a) ImportError
b) IOError
c) NameError
d) ZeroDivisionError

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.

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 try:

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

3 data = f.read()

4 except IOError:

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

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 >>> print(x)

2 Traceback (most recent call last):

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

4 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 >>> my_function()

Traceback (most recent call last):


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

3 NameError: name 'my_function' is not defined

The ZeroDivisionError built-in exception is raised in Python when a


program tries to divide a number by zero. For example:

1 >>> x = 5

2 >>> y = 0

3 >>> 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 try:

2 result = 5 / 0

3 except ZeroDivisionError:

4 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 num1 = float(input("Enter the first number: "))

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

4 if num2 == 0:

5 raise Exception("The denominator cannot be zero")

6 else:

7 quotient = num1 / num2

8 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.

5. Define the following:


a) Exception Handling
b) Throwing an exception
c) Catching an exception

xception 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 try:

2 # code that may raise an exception

3 except ExceptionType:

4 # 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 try:

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

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

4 quotient = num1 / num2

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

6 except ZeroDivisionError:

7 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 def positive_number(value):

2 if value < 0:

3 raise ValueError("Value must be positive.")

4 else:

5 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 try:

2 positive_number(-5)

3 except ValueError as e:

4 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 try:

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

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

4 result = num1 / num2

5 except ZeroDivisionError:

6 print("Cannot divide by zero.")

7 except ValueError:

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

9 else:

10 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 try:

2 # some code that may raise an exception

3 result = int("a")

4 except ValueError as ve:

5 # code to handle the exception

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

7 except Exception as e:

8 # generic exception handler

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

10 else:

11 # code to be executed if there is no exception

12 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")
• The statements inside the finally block are always executed regardless of whether an
exception occurred in the try block or not.

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 import math

3 try:

4 x = float(input("Enter a number to find its square root: "))

5 result = math.sqrt(x, 2) # providing two arguments instead of one

6 except ValueError as ve:

7 print("Error: Invalid argument for sqrt() method.")

8 print("Message:", str(ve))

9 except Exception as e:

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

11 else:

12 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 print (" Learning Exceptions...")

2 try:

3 num1= int(input ("Enter the first number"))

4 num2=int(input("Enter the second number"))

5 quotient=(num1/num2)

6 print ("Both the numbers entered were correct")

7 except ValueError: # to enter only integers

8 print (" Please enter only numbers")

9 except ZeroDivisionError: # Denominator should not be zero

10 print(" Number 2 should not be zero")

11 else:

12 print(" Great .. you are a good programmer")

13 finally: # to be executed at the end

14 print(" JOB OVER... GO GET SOME REST")

General Built-in Python Exceptions:

Exception Description
Name

EOFError Raised when one of the built-in functions (input( )) hits an end-of-file
condition (EOF) without reading any data. (NOTE. the file.read( ) and
file.readline( ) methods return an empty string when they hit EOF.)
IO Error Raised when an I/O operation (such as a print statement, the built-in
open( ) function or a method of a file object) fails for an I/O-related
reason, e.g., “file not found” or “disk full”.

NameError Raised when a local or global name is not found. This applies only to
unqualified names. The associated value is an error message that
includes the name that could not be found.

IndexError Raised when a sequence subscript is out of range, e.g., from a list of
length 4 if you try to read a value of index like 8 or E8 etc. (Slice
indices are silently truncated to fall in the allowed range ; if an index
is not a plain integer, TypeError is raised.)

ImportError Raised when an import statement fails to find the module definition
or when a from … import fails to find a name that is to be imported.
TypeError Raised when an operation or function is applied to an object of
inappropriate type, e.g., if you try to compute a square-root of a
string value. The associated value is a string giving details about the
type mismatch.

ValueError Raised when a built-in operation or function receives an argument


that has the right type but an inappropriate value, and the situation
is not described by a more precise exception such as IndexError.

ZeroDivision Raised when the second argument of a division or modulo operation


Error is zero.

OverflowErro Raised when the result of an arithmetic operation is too large to be


r represented.
KeyError Raised when a mapping (dictionary) key is not found in the set of
existing keys

ImportError Raised when the module given with import statement is not found.

KeyboardInte Raised when keys Esc, Del or Ctrl+C is pressed during program
rrupt execution and normal program flow gets disturbed.

Practice Programs
1. Write a Python program that takes two numbers as input from the user and calculates
the quotient of the two numbers. Handle the exceptions that may occur during the
program execution, such as invalid input or division by zero.

2. Write a Python program that reads a file and displays its contents on the screen.
Handle the exceptions that may occur during the program execution, such as the file not
found error or file reading error.

3. Write a Python program that takes a list of integers as input from the user and
calculates the average of the numbers. Handle the exceptions that may occur during the
program execution, such as invalid input or division by zero.
4. Write a Python program that reads a CSV file and displays its contents on the screen.
Handle the exceptions that may occur during the program execution, such as the file not
found error or file reading error.

5. Write a Python program that takes a string as input from the user and converts it to
an integer. Handle the exceptions that may occur during the program execution, such as
invalid input or string conversion error.

6. Write a Python program that takes a list of numbers as input from the user and finds
the maximum and minimum numbers in the list. Handle the exceptions that may occur
during the program execution, such as invalid input or empty list error.

7. Write a Python program that reads a file and writes its contents to another file. Handle
the exceptions that may occur during the program execution, such as the file not found
error or file reading/writing error.

8. Write a Python program that takes two strings as input from the user and
concatenates them. Handle the exceptions that may occur during the program
execution, such as invalid input or string concatenation error.

9. Write a Python program that reads a text file and counts the number of words in it.
Handle the exceptions that may occur during the program execution, such as the file not
found error or file reading error.

10. Write a Python program that takes a string as input from the user and reverses it.
Handle the exceptions that may occur during the program execution, such as invalid
input or string reversal error.

You might also like