0% found this document useful (0 votes)
27 views3 pages

Exception Handling in Python

Uploaded by

raghavkrishna.b
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)
27 views3 pages

Exception Handling in Python

Uploaded by

raghavkrishna.b
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

Exception Handling – Worksheet

Answer Key

1. c) Yes, it allows handling different exceptions separately.


2. c) To close resources those were opened in the 'try' block, regardlessof
whether an exception occurred or not.
3. c) NullPointerException
4. a) An error that occurs during runtime
5. a) Error: can’t divide by zero
b) Result: 2.0
c) Error: Invalid input, please enter a valid number
6. An exception may be raised even if the program is syntactically correct. – True
7. Error: Invalid value conversion
8. i. Entered Number: 2
ii. Error: Invalid input
9. output:
The element is s
TypeError: unsupported operand type(s) for +: 'int' and 'str'
c) Type Error
10. c) print(‘5’+3)
11. a) The standard exceptions are automatically imported in Python
programs.
12. a) Both A and R are true and R is correct explanation of A
13. a) Both A and R are true and R is correct explanation of A
14. b) ZeroDivisionError
15. c) when no exception occurs
16. a) yes, like except TypeError, SyntaxError ,…
17. output
i) 1 ii) 2 iii) 2
2 1

18. c) Exception
19. a) No Error
20. c) Index Error
21. b) Name Error
22. d) Type Error
23. d) Bye (printed infinite number of times)
24. c) Assignment Error
25. a) an object
26. d) IOError
27. a) Indentation Error
28. b) locals()
print(dir(locals()['__builtins__']))
# Above code returns all the builtin exceptions in Python in the form of list
29. c) Index Error
30. b) Identifiers
31. b) only one
32. a) ValueError
33. a) Python!
34. except, finally
35. #Program to raise ValueError exception
try:
n=int(input("Enter an integer:"))
except ValueError:
print("ValueError:Invalid literal for int()")
else:
print("Entered value is a valid integer")
finally:
print("Task over")
36. #Program to raise IndexError exception
L=[12,34,65,45,23]
print(L)
try:
n=int(input("Enter the index position of element you want to delete:"))
[Link](n)
except IndexError:
print("IndexError:List index out of range")
else:
print("New List is",L)
finally:
print("Task over")
37. #Program to handle ArithmeticError exception
n1,n2=eval(input("Enter the dividend and divisor:"))
try:
Q=n1/n2
except ArithmeticError as AE:
print(AE,” Divisor can’t be zero”)
else:
print("Quotient is",Q)
finally:
print("Task over")
38. #Program to handle ZeroDivisionError exception
def divide(a,b):
try:
c=a/b
except ZeroDivisionError:
print("ZeroDivisionError:Divisor can't be zero")
else:
print("Quotient is",c)
finally:
print("Task over")
divide(12,5)
divide(4,0)
39. 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")
40. ArithmeticError:
It is an error occurs while performing mathematical operations or when
arithmetic operation fails to produce the result.
Types:
i) OverFlowError
ii) ZeroDivisionError
iii) FloatingPointError

Common questions

Powered by AI

A NullPointerException indicates that a program is attempting to use an object reference that has not been initialized or is set to null. This exception is mostly associated with languages like Java and can lead to program crashes if not handled properly. While Java is a compiled language, interpreted languages like Python use exceptions such as TypeError or AttributeError to signal similar issues .

An 'IndexError' occurs when attempting to access a list element at an invalid or non-existent index. To prevent this, one can implement checks to ensure the index is within the valid range by using the len() function. Error handling with try-except blocks can also provide a fallback mechanism when out-of-bounds access occurs .

ZeroDivisionError is addressed in exception handling by including an 'except ZeroDivisionError' clause to handle division attempts by zero explicitly. It is crucial to catch this exception to prevent program crashes and undefined behaviors. Handling it gracefully allows for user-friendly messages, maintaining robustness and avoiding application termination .

An 'IndentationError' might arise when there is a mismatch in indentation levels within a Python block structure, such as a function or loop. It can halt program execution, as Python relies on indentation for defining code block boundaries. This error forces developers to correct the visual structure of the code to ensure logical flow .

Python automatically treats exceptions using built-in standard exceptions that cover a range of common errors. Developers can gain insight into these exceptions by using the 'dir()' function on the '__builtins__' module, which returns a list of all standard exceptions. This aids in understanding potential pitfalls and necessary safeguards in exception handling .

Specific exceptions are handled separately using multiple 'except' clauses tailored to different exception types. This allows for precise and appropriate responses to different error conditions, improving program robustness. Handling exceptions separately increases code clarity and facilitates debugging by isolating erroneous situations with specific actions or messages .

The 'finally' block is used in exception handling to execute code that must run whether an exception occurs or not. This block is typically used for releasing resources like file handles or closing database connections that were opened in a 'try' block. Regardless of whether an exception has been thrown and caught, the 'finally' block executes after the 'try' and 'except' blocks .

Python identifies misuse of identifiers through NameError, which occurs when a local or global name is not found. This typically results in program interruption, highlighting the need for debugging to ensure variables and functions are properly defined and accessible within the intended scope. Misuse can stem from typos or logical errors in code .

A 'TypeError' occurs when an operation or function is applied to an object of inappropriate type. For example, trying to concatenate a string with an integer without proper type conversion results in a TypeError. This exception indicates a mismatch in expected data types, which can arise during arithmetic operations, function calls, or method invocations where types are not compatible .

Python's built-in exceptions are automatically imported into Python programs, making them readily available for use without needing explicit import statements. This feature is beneficial as it simplifies code writing and ensures that exception handling is consistent and easily implemented across various programs. It saves time and reduces code complexity for developers .

You might also like