0% found this document useful (0 votes)
2 views17 pages

Exception Handling in Python

The document is a comprehensive study guide for Computer Science for PUC-II students, covering the complete syllabus as per the PU Board pattern. It includes chapter-wise notes, important definitions, solved examples, previous year question papers, model papers, and practical lab manuals. The content is designed to be simple and easy to understand, prepared by experienced faculty, and focuses on exam-oriented preparation material.

Uploaded by

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

Exception Handling in Python

The document is a comprehensive study guide for Computer Science for PUC-II students, covering the complete syllabus as per the PU Board pattern. It includes chapter-wise notes, important definitions, solved examples, previous year question papers, model papers, and practical lab manuals. The content is designed to be simple and easy to understand, prepared by experienced faculty, and focuses on exam-oriented preparation material.

Uploaded by

sureshbilagodi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
COMPUTER SCIENC= CORER A COMPLETE STUDY COMPANION PUC-II Science & Commerce Cue eee Le @ Complete Syllabus Coverage as PU Board Pattern @ Chapter-wise Notes & Concept Explanation © Important Definitions & Key Points Solved Examples and Programs & Previous Year Question Papers Analysis . © Model Question Papers & Practice Tests & Practical Lab Manual with Output Shri. Guruprasad TR © One Mark, Two Mark & Long Answer Questions NCA, BLP PGD (Cyt See) Y . Mahesh PU College, Chitradurga @ flowcharts, Algorithms & Program Logic @ Exam-Oriented Preparation Material Suri, Shivaloam ar H. u © MCQsand Objective Type Questions Polyfibers Junior College, Kumarapatnam & Simple and Easy-to-Understand Content @ Prepared by Experienced Faculty ul . ee me a Tel) PEE PEP tay Lie) Ren un Cena GYAAN PUBLICATION, DHARWAD Allrights reserved © Published by New Edition Price Pages Size Publisher / Author No part of this publication may be re-produced, stored in a retrieval system or distributed in any form or by any means, electronic, mechanical, photocopying, recording, scanning, web or otherwise without the written permission of the publisher. Gyaan Publication has obtained all the information in this book from the sources believed to be reliable and true. However, Gyaan or its editors or authors or illustrators don’t take any responsiblity for the absolute accuracy of any information published and the damages or loss suffered thereupon. Gyaan Publication, Dharwad. June-2026 300/- iv+228 Demy 1/4th co [Link] Sr. Ne CHAPTERS mc Marks | MCQ | SA-2 SA-3 1A_ | [Link] 1. |Exception Handling in 6 5 2 1 01 Python 2. |File Handling in Python 6 5 2 1 13. 3. |Stack 9 8 1 1 if 24 4. |Queue 9 8 1 1 1 38 5. |Sorting 12 10 2 1 i 49 6. |Searching 12 10 1 1 1 59 7. |Understanding Data 6 5 1 67 8. |Database Concepts 13 12 2 1 1 1 80 9. |Structured Query 17 15 5 1 1 1 95 Language 10. |Computer Networks 13: 12 2 1 1 1 129 11. |Data Communication 10 9 2 1 1 149 12. | Security Aspects 7 6 1 1 169 13. | Project based learning - - Total 120 105 | 20/20 | 4/7 4/7 | 6/10 LABMANUAL 184 KSEAB THREE Model Question Papers SOLVED. 200 2026 Annual Exam - 1, 2 Question Papers 215 SUBJECT : COMPUTER SCIENCE CLASS : I PUC Question Paper Question Type No. of Marks Part Questions PART-A MCQ’s S/S 15/15 PART -A Fillin the blanks 05/05 05/05 PART-B Short Answer (SA=02 Marks) 04/07 8/14 PART-C Short Answer (SA=03 Marks) 04/07 12/21 PART-D Short Answer (SA= 03 Marks) 06/10 30/50 Total 34/44 70/120 01 Chapter Blueprint Plan 1.1 Introduction Sometimes a Python program may not run, or it may run but give wrong or unexpected results because of syntax, runtime, or logical errors. These errors are called exceptions, and they can happen automatically or be created and handled in the program. Exceptions can also be forcefully triggered and handled through program code. 1.2 Types of Error: An error is a term which is used to describe any issue that arises unexpectedly that causes a computer do not functioning properly. The process of finding and climinating the errors is called Debugging. In Python We have 2 types of Errors: 1, Syntax Error / Compile-Time Error 2. Runtime Error Syntax Error: * Syntax errors occur when the rules of the Python language are not followed. Also known as parsing errors. + The interpreter detects these before execution and the program does not run until they are fixed. © Python displays the error name and a brief description with a suggestion. =int(input(“enter a no”)) if x%2==0 print(x) File “”, line 2 if x%2=20 SyntaxError: invalid syntax for i in range(1,1@): print(i) nput-2-c8efSb8F4e59>”, line? File” in 1 a=10 2 b=int(input(“enter a no:”)) 3 print(a/b) ZerodivisionError: division by zero Note : Observe that there is nothing wrong with the program syntax, it is only when we try to divide on integer with zero, on exception is generated. Example - a=[7,9,45,10,23] nt (input (“enter a no:”)) for i in range(n): print (afi]) enter a no:3 7 9 45 a=[7,9,45,10,23] nt (input(“enter a no:”)) for i in range(n): print (a[i]) enter a no:8 7 9 45 ot) 23 IndexError in 2 n=int(input (“enter a no:”)) 3 for i in range(n): =--4 — print(afi]) IndexError: list index out of range Note : Only When we are typing to access a list element with an non existing indes on exption is generated Example -; x=int(input(“enter a no:”)) print (x**2) enter a no:5 25 nt(input(“enter a no:”)) print (x**2) enter a no:itnagar ValueError in > 1 xsint(input (“enter a no:”)) 2 print(x**2) ValueError: invalid literal for int() with Note : Only When we are trying 10 convert a string to integer the exception generated. 1.4Bi * Built-in exceptions are predefined error types in Python that handle common problems that occur while a program runs, in Exceptions © When a built-in exception occurs, the handler runs, shows the error name and reason and the programmer takes action to fix or manage it. © Python’s standard library provides a collection of built-in exceptions with standardized solutions. Some of the commonly occurring built-in exceptions in be raised in Python are explained in Table 1.1. in exceptions in Python et that oH BaseException The base class for all built-in) exceptions, Exception The base class for all non-exit} exceptions. ArithmeticError Base class for all errors related) to arithmetic operations. Zerol ionError| Raised when a division or| modulo operation is performed with zero as the divisor. Raised when an assert statement| fails. Assert nError Raised when an attribute| reference or assignment fails. AttributeError IndexError Raised when a sequence| subscript is out of range. KeyError Raised when a dictionary key is not found. MemoryError Raised when an operation runs out of memory. NameError Raised when a local or global! name is not found. PUC-I| COMPUTER SCIENCE EXCEPTION HANDLING IN PYTHON ‘TypeError Raised when an operation on function is applied to an object of inappropriate type. ValueError Raised when a function receives| an argument of the right type but| inappropriate value. |ModuleNotFoundError | Raised when a module cannot} be found, 1OError Raised when an I/O operation| (like reading or writing toa file) fails. FileNotFoundError| Raised when a file or directory) is requested but cannot be found. Stoplteration Raised when the next() function] is called and there are no more items in an iterator. RuntimeError Raised when a general error occurs in the program, SyntaxError Raised when there is an error in| the syntax of the code. IndentationError | Raised when there is an| indentation error in the code. Example of Built-in Exceptions: >>> print(50/0) ZeroDivisionError: division by zero >>> print(vart40) NameError: name ‘var’ is not defined >>> l0Hs* TypeError: unsupported operand type(s) for +: int” and ‘str’ Note : Programmers can also create user-defined exceptions. 1.5 Raising Exceptions © When Python detects an error, it raises an exception and runs the matching handler; programmers can also raise exceptions using raise or assert, and once an exception occurs, the rest of that code block stops executing, © Raising an exception interrupts the normal program flow and jumps to the exception handler. © Once raised, no further statements in the current code block are executed. 1.5.1 The raise Statement The raise statement can be used to throw an exception. The syntax of raise statement is: raise exception-name| (optional argument)| The argument is generally a string that is displayed when the exception is raised. Example 1: Raising a ValueError age = -5 if age < @: raise ValueError(“Age cannot be negative”) print(“Valid age”) Explanation: If the age is negative, Python raises a ValueError and stops execution. Example 2: Custom condition check marks 35 if marks < 40: raise Exception(“Student has failed”) print(“Student passed”) Following are the advantages of Raise statement © It helps us raise error exceptions when we may run into situations where execution can’t proceed. It helps us raise error in Python that is caught. Raise allows us to throw one exception at any time. It is useful when we want to work with input validations. 1.5.2 The assert Statement An assert statement in Python checks a condition, and if it is false, it raises an exception to indicate an error. Used for debugging, often to check for valid input. The syntax for assert statement assert Expression|, arguments] On encountering an assert statement, Python evaluates the expression given immediately after the assert keyword. If this expression is false, an AssertionError exception is raised which can be handled like any other exception. Example num = -10 assert num > @, “Number must be positive” print(“Valid number”) Checking positive number Explanation: Since num is negative, the condition is false and Python raises an AssertionError. [3] COMPUTER SCIENCE SCORER EXCEPTION HANDLING IN PYTHON Example 2: Valid input check age = 20 assert age 2 18, “You must be at least 18 years old” print(“Access granted”) press Purpose Used to manually [Used to test a trigger an exception | condition and raise error if false [Control Programmer decides. | Automatically raises AssertionError iftcondition fails Raises only AssertionError when and what exception toraise Can raise any exception type Exception (ype Usage Forhandling errors | For debugging and and enforcing rules | checking in programs assumptions Syntax raise Exception ype [assert condition, (message”) Input validation, custom errors, program logic “message” Testing, debugging, verifying conditions (Common use 1.6 Handling Exceptions Exception handling is a way to manage runtime errors in a Python program so it can handle problems smoothly instead of stopping suddenly. The process of writing code to manage exceptions and prevent program crashes. 1.6.1 Need for Exception Handling Exception handling helps catch and manage runtime errors so a program does not crash; Python groups errors into types, separates error-handling code from main code, identifies where the error occurs, and supports both built- in and user-defined exceptions. Need for Exception Handling in Python © Prevents program crash: Handles errors so the program does not stop suddenly. * Maintains normal flow: Allows the program to continue running even after an error. © Improves reliability: Makes programs more stable and robust. © Handles unexpected situations: Manages issues like invalid input, file errors, or division by zero. © Separates error-handling from main logic: Keeps code clean and easier to understand, * Provides meaningful error messages: Helps users and programmers understand what went wrong. © Supports recovery actions: Allows corrective steps instead of abrupt termination 1.6.2 Process of Handling Exception * Error Occurs: Python interpreter creates an exception object containing error details (type, location), © Throwing an Exception: This object is handed over to the runtime system. * Searching for Handler: The runtime system searches for an exception handler. Starts in the method where the error occurred. Ifnot found, searches backward through the call stack (the list of methods called). © Catching an Exception: When a suitable handler is found, it is executed. * Program Termination: If no handler is found in the entire call stack, the program stops. Flowchart Summary: Error —> Create Exception Object ~ Raise Exception > Search Handler in Current Method — If Found: Execute Handler (Catch) / If Not Found: Search Call Stack + If Not Found in Stack: Program Terminates Create exception v Exception is raised Exception Runtime system searches ‘handler in Ps ‘Searches for methods incall (Catching and Exception stack in reverse sequence _— Pion round (Forwarding the exeption) [perm sram terminates 1.6.3 Catching Exceptions Exceptions are caught in a try block and handled in except block. Suspicious code is placed inside try. One or more except blocks follow a try block. While executing the program, if an exception is encountered, further execution of the code inside the try block is stopped and the control is transferred to the except block. PUC-I| COMPUTER SCIENCE [4] EXCEPTION HANDLING IN PYTHON Syntax: try: [program statements where exceptions might occur] except [exception-name]: [code for exception handling if the exception-name error is encountered] Write a program to ensure that an integer is entered as input and in case any other value is entered, it displays a message ~ ‘Not a valid integer’ try: numberString = input(“Enter an integer:”) n= in(numberstring) except : print (“Error! Not a valid integer,”) Enter an integer: kv2 Error! Not a valid integer. Second Argument of the Exception Block: We can also provide a second argument (optional) for the except block, which gives a reference to the exception object. try: ficode except as : ficode for error handling here Example-1 (Program): try: num1 = 10 num2 = @ result = num1 / num2 print (result) except ZeroDivisionError: print(“Error: Cannot divide by zero”) Explanation: The code that may cause an error is inside try If division by zero occurs, the except block handles it Example-2 (Program): try: print(“result of 10/5 = ”,(10/5)) print(“result of 10/0 = ”, (10/2)) exccept ZeroDivisionError as e : print (“Exception-”, str(e)) result of 10/5 2.0 Exception- division by zero Handling Multiple Errors : Handling multiple exceptions in Python allows a single try-except block to handle different types of exceptions using multiple except blocks. This allows a program to handle various types of errors that may occur during runtime and take corrective measures accordingly. * Handling multiple except blocks in Python means writing separate handlers for different types of errors that may occur in a try block. * Each except block catches and handles a specific exception. * Used when code may raise different exceptions, Syntax try # code that may raise an exception except ExceptionTypel: # code to handle ExceptionType1 except ExceptionType2: # code to handle ExceptionType2 excep’ # code to handle all other Exceptions Example try: a = int(input(“Enter a number: ”)) b = int(input (“Enter another number: “)) result = a/b print (“Result:”, result) except ZeroDivisionError: print(“Error: Cannot divide by zero.”) except ValueError: print(“Error: Invalid input. Enter only numbers.”) except Exception: print (“Some other error occurred.”) 1.6.4 try....except....else Clause : We can put an optional else clause along with the try... except clause. An except block will be executed only if some exception is raised in the try block. But if there is no error then none of the except blocks will be executed, In this case, the statements inside the else clause Il be executed. Syntax try: # code that may raise an exception except ExceptionTypel: # code to handle ExceptionTypet except ExceptionType2: # code to handle ExceptionType1 except: # code to handle all other Exceptions else: # If there is no exception then this block get executed [5] COMPUTER SCIENCE SCORER EXCEPTION HANDLING IN PYTHON Example (Program ): print (“Handling exception using else”) numerator=50 denom=int(input(“Enter the denominator: “)) ‘quotient=(numerator/denom) print (“Division performed successfully”) except ZeroDivisionError: print (“Denominator as ZERO is not allowed”) except ValueError: print (“Only INTEGERS should be entered”) else: print (“The result of division operation is”, quotient) Ifinput result of division operation is 10.0”. 1.7 finally Clause The finally block is a part of the try-except block in Python that contains the code that is executed regardless of whether an exception is raised or not. Placed at the end, after all except and else blocks. Typically used for cleanup actions (c.g., closing files). Output includes the else block message: “The The syntax of the try-except-finally block is as follows: try: # Code that may raise an exception except ExceptionType: # Code to handle the exception finally : # code that is executed after the try-except block Behavior with Unhandled Exceptions: Ifan exception is not caught by any except block, the finally block executes first, then the exception is re-raised. Example : Program using finally block. try: x = int(input(“Enter anumber: ”)) y = int(input(“Enter another number: ”)) result = x/y print(“Result: ”, result) except ValueError: print(“Error: Invalid input”) except ZeroDivisionError: print(“Error: Division by zero”) finally: print(“Program execution completed”) Enter a number: 20 Enter another number: @ Error: Division by zero program execution completed MULTIPLE CHOICE QUESTIONS (MCQS) 1. What is an exception in Python? (a) A syntax rule violation (b) A runtime error represented as an object (©) A logical mistake in program design (d) A missing parenthesis in print statement Which of the following is also known as a parsing error? (a) Logical Error (b) Syntax Error (c) Exception (d) Runtime Error 3. Which exception is raised when an index is out of range for a sequence? (a) KeyError (b) IndexError (©) ValueError (d) AttributeError 4, What does the raise statement do? (a) Handles an exception (b) Tests a condition (c) Forcefully triggers an exception (@) Skips an error 5. Assertion (A): The finally block in exception handling always executes. Reason (R): The finally block is designed for cleanup activities that must occur regardless of error states. (a) Both A and R are true and R is the correct explanation of A. (b) Both A and R are true but R is not the correct explanation of A. (c) Ais true but R is false, (d) Ais false but R is true 6. Which block contains code that is executed only if tion is raised in the try block? (a) except (b) else (©) finally (d) catch 7. What happens if an exception is raised and no matching except block is found? (a) The program continues silently (b) The else block handles it (©) The finally block handles it (4) The program terminates 8. The assert statement raises an exception when its expression evaluates to: (a) True (b) False (c) None (A) Zero 9. Assertion (A): Every syntax error is an exception. Reason (R): SyntaxError is a built-in exception class in Python, (a) Both A and R are true and R is the correct explanation of A. (>) Both A and R are true but R is not the correct explanation of A. PUC-Il COMPUTER SCIENCE EXCEPTION HANDLING IN PYTHON 10. u. 12. 13. 14, 15, 16. 17. 18. (c) Ais true but R is false. (d) Ais false but R is true. Where should the finally block be placed? (a) Before the try block (b) Immediately after the try block (c) After all except and else blocks (d) It can be placed anywhere Which of the following will raise a NameError? (a) print(10/0) (b) print(undefined_variable) (c) int(10.5') (a) ‘27 +2 The process of creating an exception object and handing it to the runtime system is called: (a) Catching an exception (b) Throwing an exception. (c) Handling an exception (d) Raising an exception Which statement is used to test an expression and raise an AssertionError if it fails? (a) raise (b)try (©) assert (A) test What is the primary purpose of exception handling? (a) To make code run faster (b) To prevent the program from crashing abruptly (c) To improve code syntax (d) To define new data types Assertion (A): You can have multiple except blocks for a single try block. Reason (R): Different lines of code in the try block may raise different types of exceptions. (a) Both A and R are true and R is the correct explanation of A. (b) Both A and R are true but R is not the correct explanation of A (c) Ais true but R is false. (d) Ais false but R is true. Which of the following is NOT a built-in exception mentioned in the chapter? (a) Keyboardinterrupt (b) MemoryError (©) OverflowError (4) ImportError Ifan unhandled exception occurs and a finally block exists, what happens? (a) Only the finally block executes. (b) The finally block executes, then the exception is re-raised. (c) The exception is ignored after finally. (d) The program terminates before finally. Which exception is raised for incorrect indentation? (a) TabError (b) IndentationEror (c) FormatError (@) SyntaxError 19. 20. a. 23. 24. 25. 26. 27. Assertion (A): The else block in exception handling executes if an exception occurs. Reason (R): The else block is an alternative to the except block. (a) Ais true and R is correct reason. (b) Ais true and R is not correct reason. (©) Ais false and R is correct reason. (d) Ais false and R is not correct reason, Which of the following can raise a TypeError? (a) 10/0 (b) open(‘[Link]’) (©) *hello’[10] (S45 An ImportError is raised when: (a) Importing a built-in module like math (b) The imported module has syntax errors (c) The requested module definition is not found (d) Importing too many modules Which of the following exceptions is related to file ‘operations? (a) 1OError (b) ZeroDivisionError (c) NameError (d) TypeError The process of executing an exception handler is known as: (a) Throwing an exception (b) Raising an exception (©) Catching an exception (A) Creating an exception Which of the following is not a standard exception in Python? a) NameError b) 1OError ©) AssignmentError —_ d) ValueError Which of the following statements is true about the raise keyword? a) It can only be used within a function b) It can be used to throw both predefined and custom exceptions ©) It is used to handle exceptions 4d) It is used to catch exceptions What happens when an exception is raised in Python? a) The program immediately terminates b) The exception is passed silently c) The exception is propagated and can be caught in a try-except block d) The program prints a debug message and continues execution Which keyword is used to raise (throw) an exception in Python? a) catch b)throw c) raised) except (7] COMPUTER SCIENCE SCORER EXCEPTION HANDLING IN PYTHON 28. 29. 30. a. In which block is the exception actually thrown? a) try b) catch —c)finally —_) exception ‘What is the process called when an exception object is created and handed over to the runtime system for handling? a) Handling an exception b) Catching an exception c) Throwing an exception d) Ignoring an exception In the following Python code, what is the syntax error? ifx== 10 print(“x is 18”) a) The colon (:) is missing before the print statement. b) The condition has a missing parentheses. c) The colon (:) is missing after the if condition. d)_ The colon (:) is missing after the print statement. Identify the error the following programming segment(E) If marks >20 : print “Good Score” 32. 3. 34. 35. 36. a7. a) RuntimeError b) LogicalError c) KeyboardError 4) SyntaxError What happens when a syntax error is encountered in Python? (D) a) The program executes b) The program stops execution until the error is fixed. c) The program runs slower. d) The interpreter tries to correct the error automatically. What type of errors are exceptions in Python? a) Logical errors ) Syntax errors ) Runtime errors d) Parsing errors What happens when a syntax error occurs in Python? a) Program continues with incorrect output b) Program halts with a description of the error ) Program fixes the error automatically 4) Program warns but does not stop What are syntax errors also known as? a) Runtime errors b) Logical errors ) Parsing errors 4d) None of the above Which Python mode provides immediate feedback on syntax errors? a) Script mode b) Shell mode ¢) IDLE mode ) Debug mode When does a ZeroDivisionError occur? a) Dividing by a negative number b) Using a zero numerator ©) Dividing by zero 4) Using zero in mathematical expressions 38. 39. 41. 42. 4B. 45. 47. 48. 49. What does Python do when an exception is raised during execution? a) Continues execution b) Skips the error ¢) Terminates the program abruptly ) Jumps to exception handling code if present Which exception is raised when a variable is not defined? a) NameError ») ValueError ) SyntaxError 4) TypeError What does the IOError exception indicate? a) An undefined variable b) A file that cannot be opened ©) A division by zero d) An incorrect argument type Which exception is raised for incorrect indentation? a) ValueError b) TypeError ©) IndentationError —_) SyntaxError Which keyword is used to manually raise an exception? a) assert b)raise —) throw d) except ‘What happens after an exception is raised using the raise statement? a) The remaining statements in the block are executed b)_ The current block stops execution c) Execution continues in the same block d) None of the above What exception does the assert statement raise if the condition is False? a) AssertionError b) ValueError ¢) SyntaxError 4) RuntimeError What is the main purpose of exception handling? a) To debug syntax errors b) To prevent program crashes ¢) To increase execution speed d) To optimize performance Which block is used to catch exceptions in Python? a) try b) except c)else ——_d) finally Which block is always executed, irrespective of whether an exception occurred? a) try b) except c) else —_d) finally What happens if multiple except blocks are present for a single try block? a) All are executed b) The first matching block is executed ©) None are executed d) Only the last block is executed When is the else clause executed in a try...except block? PUC-I| COMPUTER SCIENCE [8] EXCEPTION HANDLING IN PYTHON 50. 51 52. 53. 54, 55. 56. 57. 58. a) b) If no exception occurs If an exception occurs c) Always executed d) Never executed Which block comes immediately after the try block? a) except b)else —c)finally dd) None What is the primary use of the finally block? a) To catch specific exceptions b) To execute cleanup code c) To handle syntax errors 4d) To ensure program optimization Which statement is true for the finally block? a) It executes only if an exception occurs b) It executes only if no exception occurs c) It executes regardless of exceptions 4d) It does not execute under any condition Which exception is handled in the following code? try: fum = int(input(“Enter a number: “)) except ValueError: print(“Invalid input!”) a) ZeroDivisionError _b) SyntaxExror ©) ValueError 4) TypeError What happens if no exception is raised in the try block? a) The except block executes b) The else block executes ) Both except and else blocks execute 4d) The program terminates What will happen if an exception not matched by any except block occurs? a) The program continues b) The program terminates ¢) The last except block is executed 4d) None of the above Ina try....except block with multiple except clauses, which block is executed first? a) The first except block b) The most specific matching block ) The last except block 4) None of the above What can be included in the raise statement for additional information? a) Exception name only b) Optional arguments like a string message ¢) Exception handling code ) None of the above What does the following code output? try: raise ValueError(“Custom error message”) 59. 60. 61 62. 65. 66. except ValueError as e: print (e) a) Nothing b) ValueError ©) Custom error message 4) Program terminates with error Which exception is user-defined? a) ImportError b) ZeroDivisionError ©) AssertionError 4) Any exception created by the programmer What is printed by the following code? t raise NameError(“Example”) except NameError: print(“NameError occurred”) a) NameError b) NameError occurred c) Example 4d) None of the above . Which exception does an assert statement raise if the expression is False? a) ValueError b) SyntaxError ) AssertionError 4) NameError What happens if the assert condition evaluates to Truc? a) The program halts b) An exception is raised ©) Execution continues 4d) The next except block is executed ‘What does the runtime system do when an exception occurs? a) Terminates the program immediately b) Searches for a handler in the call stack ©) Ignores the exception d) Converts it to. a warning ‘What happens if no handler is found in the call stack? a) The program terminates b) The exception is ignored ©) Execution continues 4d) The exception is logged but execution continues What does the following code do? try: x=1/0 except ZeroDivisionError: print(“Cannot divide by zero!”) a) Prints “Cannot divide by zero!” b) Terminates with ZeroDivisionError ©) Ignores the error 4) None of the above Which statement is valid for catching exceptions? a) Only one except block is allowed b) try block can have multiple except blocks [9] COMPUTER SCIENCE SCORER EXCEPTION HANDLING IN PYTHON 67. 68. 69, 70. 1 72. 73. 74. 75. ©) No try block is needed d) None of the above Which block will execute even if an exception is not raised? a) try b) except ©) finally 4d) None of the above Which block can have more than one occurrence in exception handling? a) try b) except c) else —_d) finally What is the output of the following code? try: print(1 / @) except ZeroDivisionError: print (“Exception handled”) finally: print(“Finally block executed”) a) Exception handled Finally block executed b) Finally block executed ) Program terminates with ZeroDivisionE ror 4d) None of the above ‘What is the purpose of a generic except block? a) Handle syntax errors b) Handle errors not specifically caught ) Optimize performanced) Ignore exceptions Which block is recommended for cleanup operations? a) try b) except ¢)finally —d) else ‘What does the following code print? try: int (“abc”) except ValueError: print(“ValueError handled”) a) ValueError b) Program terminates ©) ValucError handled — d) None of the above What happens when an exception is raised but not caught? a) The program terminates b) It continues execution c) It enters the finally block and resumes 4d) None of the above What is the purpose of an else clause in a try block? a) It is mandatory b) Executes if no exception occurs c) Always executes regardless of exceptions d) It defines error recovery steps Which exception is raised if the following code i executed and the input is abc? try: num = int(input(“Enter a number: “)) except ValueError: print (“Invalid input!”) 6. 71. B. np. 80. a) ValueError b) TypeError ©) SyntaxError 4d) NameError What does exception handling ensure? a) Errors are ignored b) Code runs faster ©) Program does not crash abruptly d) Syntax errors are corrected automatically What is the primary benefit of a try...finally strueture? a) Better syntax ) Clean termination or recovery c) Handling specific exceptions d) Ignoring runtime errors ‘What exception is raised if input() encounters EOF? a) ValueError b) EOF Error ©) TypeError 4) SyntaxError When is the OverFlowError raised? a) A file cannot be opened b) Division by zero occurs ¢) Acalculation exceeds the max limit for a numeric type d) An undefined variable is accessed What is the process of finding an exception handler called? a) Raising an exception b) Catching an exception ) Searching the call stack 4d) None of the above FILL IN THE BLANKS The contains information about the error like its type and location in the program. (exception object) are exceptions that are predefined in the Python interpreter/compiler. (Built-in exceptions) The clause in a try statement executes only when no exception occurs in the try block. (else) A single try block can be followed by multiple blocks to handle different exceptions. (except) When an exception is raised using the raise statement, the program’s normal flow i (interrupted) The exception is raised when the input() function encounters an unexpected end-of-file. (EOFError) The process of creating an exception object and handing it to the runtime system is called an exception. (throwing) The exception is raised when there’s incorrect indentation in Python code.(IndentationError) The block is commonly used for cleanup activities like closing files. (finally) PUC-I| COMPUTER SCIENCE [10] EXCEPTION HANDLING IN PYTHON 10. i. 14, 15. 16. 17. 18. 19, 20. 22. 23. 24. 2. 26. oF. 28. 29, 30. The is true and raise an exception if it’s false. (assert) Exceptions that are not built-in but created by programmers are called (user-defined) A_____ error occurs when the rules of the | 33- programming language are not followed.(Syntax) Errors that occur during program execution and disruptits normal flowar ecalled (Exceptions) The block in Python is used to catch exceptions and handle them appropriately. (except) Adivision by zero operation raises the exception. (ZeroDivisionError) The exception is raised when a variable is referenced but has not been defined.(NameError) The Python statement used to manually raise an exception is (raise) A block is always executed, regardless of whether an exception occurred or not. (finally) | 39, The exception occurs when the file specified in a program cannot be opened. (IOError) The process of identifying and handling exceptions | 40, is called (Exception handling) The fatement is conditions and raise an AssertionError if the condition evaluates to False.(assert) ‘A block of code suspected to raise exceptions is enclosed within a A(n)____. _exception can be created by programmers to handle specific errors not covered | 2) by built-in exceptions. (user-defined) The exception raised when an input operation hits | 3) the end of the file without reading any data is. (EOFError) 4) Python provides a structured block of text, known as | 5) » that contains information about the sequence | 6) of function calls during an exception. (traceback) The exceptions. (else) A(n) value is passed to a built-in method or operation. (ValueError) 10) ‘The exception raised due to incorrect indentation in | 11) Python is. (IndentationError) 12) The Python runtime system searches the 13) to find an appropriate handler for the raised exception. (call stack) 14) A(n) exception occurs when an index is out of the valid range of a sequence.(IndexError) statement is used to test if a condition | 31. exceptions 32. 34. 35. 36. 37. ised in Python to test | 41, block. (try) 1) clause in Python is executed only if | 7) the try block completes successfully with out any | 8) exception is raised when an invalid | 9) The process of identifying a suitable handler for a raised exception is called the exception. (catching) The exception raised when the requested module is not found is (importError) The exception raised when a key is not found in a dictionary is (KeyError) The exception raised when a calculation exceeds the maximum limit for a numeric type is (OverflowError) The block is placed after a try block to handle multiple exceptions using separate handlers. (except) When no specific handler is defined for an exception, a generic block can be used. (except) The exception raised when the user presses an interrupt key like Ctrl+C is_.(Keyboard Interrupt) 38. The method or block of code responsible for responding toa specifi type of exception is called a(n) (exception handler) Python’s standard library includes numerous exceptions to handle commonly occurring errors. (built-in) When an exception occurs, the normal flow of the program is . (interrupted) The try block is mandatory when using the clause in Python exception handling. (except) DESCRIPTIVE 2MARKS QUESTIONS, What happens when an error is detected in a Python program? What is exception ? Mention any one type of exception. What is built-in exceptions? Mention any one type of built-in exceptions. What is the role of an exception handler in Python’? Difference between SyntaxError and ValueError. Define the following a) IOError b) Keyboardinterrupt Define i) Keyboardinterrupt ii) ImportError Define the terms i) TypeError ii) NameError Difference between ZeroDivisionError and IndexError Define a) EOFError —_b) IndentationError Define a) TypeError —_b) OverFlowError Mention the two types of exceptions. What is the purpose of the raise statement in Python. Write What is the purpose of the assert statement in Python. Write its syntax. (E) [1] COMPUTER SCIENCE SCORER EXCEPTION HANDLING IN PYTHON 15) 16. 7. 18, 19. 20. 21 22. Ans:A traceback is as 23. What is the purpose of the finally clause in a Python try statement, and where should it be placed? Define the term exception in Python. What does the finally block do in Python? Differentiate between the raise and assert statements in Python. What is the purpose of the try block in exception handling? What is an EOFError, and when does it occur? Explain the purpose of the else clause in exception handling. What is a traceback in Python? uctured block of text displayed when an exception is raised. It provides information about the sequence of function calls leading to the exception, helping in debugging the program. What is the purpose of the call stack in exception handling? Ans:The call stack is a list of function calls made during 1) 2) 3) 4) 5) 6) 7) 8) %» 10) n) 12) 13) 14) 15) program execution. When an exception occurs, Python searches the call stack to find an appropriate exception handler. 3 Marks questions What is exception handling ? Mention any two keywords used in exception handling. What is exception handling? Why is it important in programming? What is exception ? Mention types of exception What is built-in exceptions? Mention two types of built-in exceptions. ‘What is the purpose of built-in exceptions in Python? Provide two examples of built-in exceptions. Explain any three built-in exceptions in python. Explain the following terms a) SyntaxError b) ValucError c) IOError Explain the following terms i) KeyboardInterrupt ii) ImportError iii) EOFEmor What is the purpose of raise statement ? Write its syntax and example. Define the following: a) Exception Handling b) Throwing an exception c) Catching an exception Difference between raise and try-except blocks. Write any three need for exception handling? What is an exception object in Python and what information does it contain? What is the purpose of using an else clause in a try...except block in Python? Explain with an example, Write a note on finally clause. 16) What is the purpose of the assert statement in Python? Provide an example. 17) Explain the following terms (E) a) ZeroDivisionError _b) IndexError ©) NameError 4) IndentationError ©) TypeError 18) Explain any five built-in exceptions in python. 19) Explain the following a) SyntxError ) ValueError ©) IOError 4) ImportError e) EOF Error 20) Explain the purpose of a) exception handling b) raise statement c) assert statement d) catching exceptions e) finally clause 21) Briefly explain try, except and finally block. 22) What will happen if an exception is not caught by a try-except block in Python? 23) Explain try-except in Python with a program example. 24) What is the use of finally clause ? Give a program example. 25) What is the purpose of the else block in a try...except...else statement in Python? Give an program example. 26) Explain any 3 common built-in exceptions in Python and explain what each one is used for. 27. Differentiate between raise and assert in Python 28. How does Python handle uncaught exceptions? ttee MCQKEY ANSWER a 7d | 8b | 90 loc | ib [12 ic [ i4b | 15a | 16b [ 17b | 18d iad | 20d | 210 | 22a | 23¢ | 240 25b | 26a | 27¢ [ 28a | 290 | 300 sid | 32b | 33¢ [| 34b | 350 | 36d 37.c | 38d | 39a [| 40b [atc [420 436 | 44a [ 45» [ 4ob | 47a [48d 49a | 50a | sib | 520 [ 530 | sab ssb | s6b | s7b [| 58¢ | 59a | 60d lc | 6c | 6b | 64a | 65.0 | 66d orc | 8b | 69a [ 7b | 7c | 726 Ba | 746 | 75a | 76¢ | 7b | 78b 79.c | 80.0 PUC-I| COMPUTER SCIENCE [2] Other Books from our Publications GYAAN PUBLICATION DHA ©: 79750 89350 / 7483

You might also like