Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
100%
(1)
100% found this document useful (1 vote)
3K views
22 pages
Exception Handling - Preeti Arora
Computer Science EXCEPTIONAL HANDLING class 12
Uploaded by
shruthisahasra07
AI-enhanced title
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
Download
Save
Save Exception Handling - Preeti Arora (1) For Later
Share
100%
100% found this document useful, undefined
0%
, undefined
Print
Embed
Report
100%
(1)
100% found this document useful (1 vote)
3K views
22 pages
Exception Handling - Preeti Arora
Computer Science EXCEPTIONAL HANDLING class 12
Uploaded by
shruthisahasra07
AI-enhanced title
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
Carousel Previous
Carousel Next
Download
Save
Save Exception Handling - Preeti Arora (1) For Later
Share
100%
100% found this document useful, undefined
0%
, undefined
Print
Embed
Report
Download
Save Exception Handling - Preeti Arora (1) For Later
You are on page 1
/ 22
Search
Fullscreen
3.1 INTRODUCTION Apart from computer programs that we code, an exception or error or unusual condition can occur even in our daily life. Consider a real-life scenario—we leave our house for office by car. On the way, the tyre bursts and we are forced to stop the car and replace the tyre. In this scenario, the punctured tyre is the exception that has occurred unexpectedly. In such a situation, we are required to carry along a spare tyre so that we can change the punctured tyre then and there and continue with our journey. This concept is similar to exception handling in computer programming. Normal Flow Exception Handling Likewise, when we are browsing a web page and suddenly that web page is unreachable because there is no network connection or there is no microphone available to create an audio recording— these are examples of exceptions or errors. Sometimes an application can recover from an error and still provide normal, expected behaviour, ‘sometimes errors get reported to the user, sometimes they get logged to a file, etc. It depends on the specific error and the application. The same is applicable in the field of computer programming also. 3.2 ERRORS IN PYTHON AND DEBUGGING Most application codes written for developing applications have errors in them. When our application suddenly freezes for no apparent reason, it is usually because of an error. But we all understand that programs have to deal with these errors. ‘The process of finding errors in a program is termed as Debugging. Due to errors, a program may not execute or may generate wrong output, So, it becomes necessary to find and remove errors for successful execution of a program. Errors in Python are classified mainly into three types: -@) Syntax Error (b) Run-time Error © Logical Error™~ 3.2.1 Syntax Error A A syntax error is an error in the syntax of a sequence of characters or tokens that is inteng be written in a particular programming language. These types of errors are generated Whe = violate the syntax or, in other words, the grammatical rules of a programming language, Saat errors are the most common type of errors and are easily traceable. Some examples of p, : - “a syntax errors are: 1. Incorrect indentation 2. Misspelling a keyword 3. Leaving out a symbol such as colon (:), comma (,) or parentheses (()). They can be corrected by the user as the reason for the error and an appropriate message ox what is wrong in the program is displayed. For example, eee eee >>> BEint ‘Hello world’ SyntaxError: Missing parentheses in call to ‘print Did you mean print(...)? >>> Fig. 3.1: Syntax Error: Invali Syntax ‘The given statement is an example of syntax error as it violates the language protocol by not giving Parentheses() with the print() function. So, the corrected statement should be: >>> B lo world') © world However, some syntactical errors are quite hard to find. Python is case-sensitive, so we may use the ‘wrong case for a variable and find out that the variable isn't quite working as we thought it would For example, | [BFaceback (most recent cali tasty? | | File "
", line 1, in
|, Print (4+5) [Mamezrror: nane ‘Print’ 4s not defined. pid |: feeu means speaee.t In the above example, we have typed the Print() statement instead of print(), which is syntactically wrong and needs to be corrected. So, the correct statement will be: >>> print (445) 9 Most syntactical errors occur at t} out for us. Fixing the error is mad considerable accuracy. he time of program execution and the interpreter points them le easy because the interpreter generally tells us what to fix withfe" —————— — Syntaxerror: losin Wisteria T ‘J pares tatement 2 opening parenthenia (re nemt™ I goalie mens etn J' does not match SyntaxError: incompieta iapwc 7” *Statemen >>>jprant ‘Hello! —— Lete input J Minaing pares Deint(y pppemehonens in call to ‘print’. _——————™ aStatement 3 | Lan \syntaxzrror: invaiia Statement & pe>gor 4 in range(io) 7 * irint (4) syntaxError: expected statement 5 | Statement on line :77 A" indented block after ‘for’ | Fig. 3.2: Other types of Syntax Errors er i etus understand the reason behind the occurrence of each error given in the above example. L statement 1 generates syntax error because of improper closing bracket (square bracket instead of parenthesis). 2, Statement 2 generates syntax error because of missing colon (:) after ‘if’ keyword to end if statement. 4, statement 3 generates syntax error because of missing parentheses () with print() method. 4, Statement 4 generates syntax error because of use of semicolon instead of comma in a list declaration. 5, Statement 5 generates syntax error because of improper indentation. 3.2.2 Run-time Error ‘srun-time error occurs after Python interpreter interprets the code we write and the computer bexins to execute it. Run-time errors come in different types and some are hard to find. We know we have a run-time error when the application suddenly stops running and displays 8m error (exception) dialog box or when the user complains about erroneous output. It usually results in abnormal program termination during execution. For example, >>>]10* (1/0) Traceback (most recent call last): ‘File "
", line 1, in
10* (1/0) ZeroDivisionError: division by zero Fig. 3.3: Example of Run-time Error The above statement is syntactically correct but won't yield any output, Instead, it shall generate anerror as division of any number by 0 will result in an error upon execution and illegal program termination. Some examples of Python run-time errors are: 1. Division by zero 2. Performing an operation on incompatible types 3. Using an identifier variable which has not been defined 4. Accessing a list element, dictionary value or object attribute which doesn’t exist 5. Trying to access a file that doesn’t exist et 2never part Of the norma} Ds and unexpected ‘situations and they ar unusual ETM: Errors are exceptiona, ota pregeem fons are usually run-time erp. Excepti stormed as Exceptions: In Python, such unusual situations are termed as Excep' tion but the program behay, Since the program interprets Successfully eye tifficult to Identify these errors. n 3.2.3 Logical Errors ae A logical error/bug (called semantic error) dot not § incorrectly and produces undesired /wronk Out ; r it, It is sometimes ¢ when logical errors are present In It, Te ee es fund without are the most difficult to fix. They ocelt when the prog! crash + incorrect result. The error Is caused by a mistake in the program 5 logic. We wor, ge because no syntax OF run-time error has occurred. Logical errors but produces get an error messa ‘al errors aret me for calculations. dulus operator in place Some examples of logic «Using the wrong variable na + Using integer division or mo + Giving wrong operator precedence. We will have to find the problem on our own by reviewing all the relevant parts of the code, For example, ifwe wish to find the average of two numbers, 10 and 12, and we write the code ag 10 +12. it will run successfully and produce the result 16, which is wrong. The correct code ty 2 J find the average should have been (10 + 12)/2 to get the output a For example, of division operator is 11. Yilustrating Logical Error x = float(input ("Enter a number: y = float(input ("Enter a number: z= xty/2 Drint('The average of the two numbers you have entered is:',2) ‘The above example should calculate the average of the two numbers the user enters. But because of the order of operations in arithmetic (division is evaluated before addition), the program will not give the right answer; this is known as logical error. Enter a number: 3 Enter a number: 4 "The average of the two numbers you have entered is:5.0) As a result, we will get 5.0 as the output instead of 3.5. To rectify this problem, we will simply add parentheses: z = (x+y)/2 Wilusteating Logical Error x = float (input (‘Enter a numbe: y = float(input (‘Enter a nunbe: Bs ony /2 print('tThe average of the two numbers you have entered 4: » sity Hence, now we will get the right result as 3.5 lenter a numbe: lenter a number: 43.2.4 What is Exception Handling very programming language that we wo! Bs ome mechanism to handle an coe aie occurs during @ program execution. Likewise hon also provides a complete mechanism for handling an error when it occurs. This mechanism. js called Exception Handling. gxception: Technically, an error is termed as Sl Oi Exception. An exception is an error that happens OC eee during the execution of a program. If an exception js not caught, the program ts terminated. Fig. 3.4: An Exception ‘Thus, an exception can be described as an interrupt or an event triggered during the normal flow of the execution of a program, which is to be handled carefully. when an exception is raised on account of some error, the program must contain code to catch this exception and handle it properly, | CTM: Exception refers to an abnormal condition that arises during the program execution. Let us discuss some important terms related to Exception Handling: (Traceback: The lengthy error message that is shown when an exception occurs during the program run is called a traceback. The traceback is a detailed report that gives information regarding the line number(s) along with the function calls that caused the exception. (i) Try block: Try block constitutes a set of codes that might have an exception thrown in it. If any code within the try statement causes an error, execution of the code will stop and jump to the except statement. (iii) ‘except’ block or ‘catch’ block: Whenever some error or exception is to be handled, it is done using ‘except’ block which stands for exception. (iv) ‘throw’ or ‘raise’ block: ‘throw’ is an action in response to an exception (error/unusual condition). When a program on execution encounters an abnormal condition, an object of this exception is created or instantiated and ‘thrown’ or ‘raised’ to the code responsible to catch/handle it. (v) Unhandled, uncaught Exception: An exception that leads to abnormal termination of a program due to non-execution of an exception thrown is termed as unhandled or uncaught exception. This is the result of an exception which was thrown or-raised but never caught. (ETM: Errors detected during execution are called exceptions. In other words, an exception is an error that ‘occurs while a program Is running. They indicate something unusual has happened in the program. 3.3 STANDARD EXCEPTIONS IN PYTHON Python provides us a way to handle exceptions so that the script does not terminate but executes some specified code when an exception occurs. This concept is called Exception Handling. ‘An exception can be addressed by its name. Python has some built-in exception names for common - exceptions. If required, a programmer can also define his/her own exceptions. = Exception Handling~ When an exception occurs in the program, we say that exception was raised or thrown, Ney we deal with it and say it is handled or caught. And the code written to handle it is known : exception handler. For handling exceptional situations Python provides— 1, raise statement to raise exception in the program. 2. try... except statement for catching and handling errors (which will be taken up in “Handling Exceptions in Python’ section). © raise Statement: raise statement allows the program to force a specified exception to occur at Tun-time, Python automatically raises an exception when it encounters an error during the program execution. Once an exception is raised/thrown, it is up to caller function to either handle it using try/except statement or let it propagate further, ———— Use raise to force an exception: Came Fig. 3.5(a): raise statement Syntax: raise [exception name [, message/argument][, traceback]] Here, + exception name is the type of error, which can be string, class or object. It is an instance of exception class. argument is the value/parameter passed to the class. It is a short message that describes the error. We can also give our own message for notifying error to the user. As the argument is optional its default value None is used in case the argument is not provi ided. traceback section succeeds the argument when any exception is raised or thrown. [ CTM: raise statement allows us to throw an exception at any time, For example, % = 20 af (x > 5): raise Exception('x should not exceed 5') Output: Traceback (most recent call last)? File "C:/Users/User4 /AppData/Local/Programs/P lython/Python311/3.7_1.py", line 3, in
>> Fig. 3.5(b): raising/throwing an exception We will now learn about some standard built-in exceptions available which are described iM Table 3.1.> Table 3.1: Common Python Exceptions OS Ca ameErTOr Ralsed when an identifier is not found in the local or global namespace. or Raised when an i sypeerr anaes Operation or function is attempted that is invalid for the specified valueError Ralsed when a built-in operation or function receives an argument that has the right type but an inappropriate value. geroDivisionError Raised when division or modulo by zero takes place for all numeric types. qtrbuteError Raised when an object does not find an attribute. KeyError Raised when a mapping (dictionary) key is not found in the set of existing keys. indentationError — Raised due to incorrect indentation. JOError Raised if the file requested cannot be opened, or failure of /O operation. indexError Raised when an index is not found in a sequence, ie., out of range or out of bounds. importError Raised if Python cannot find the module requested for in a program. EOFEror Raised when one of the file methods, (ie., read(), readline() or readlines(), tries to read beyond the file. syntaxError Raised when there is an error in Python syntax. RuntimeError Raised when an error does not fall under any specific exception category defined above. All the above pre-defined exceptions can be used with raise statement. Let us discuss some commonly generated exceptions. (a) NameError: This type of exception occurs when we are trying to use a variable that doesn’t exist in the current environment. It is raised when a function name or variable name is not found in the local or global namespace. If we get a NameError, check whether the variable name or function name has been typed correctly or not, has been given in quotes or defined somewhere else where it is not destined/required. Remember that local variables are local. We cannot refer to them from outside the module/function where they are defined. For example, Adding two numbers num = 10 num2 = 20 print("sum of two numbers=", num1+num3) Output: [Traceback (most recent call last): File "Cc: /Users/User4/hppData/Local/Progra ims /Python/Python311/prog_excep2.py", line 5, in < lmodule> print ("sum of two numbers=", numi+num3) lINameError: name ‘num3' is not defined. Did you mean: 'numi'? >>> Fig, 3.6(a): NameError exceptionThe given screenshot gives the description about NameError, which consists of— (i) Traceback, which describes a list of the functions which were running and display the time of occurrence of the exception. Ved a (it) The second line defines the path where in the program the exception has occurray_ name of the program, which Is prog.excep2.py in the given example along with number, ling (iii) The third line shows the actual place of error, i.¢., the statement in which the erro; occurred which is print() method. ha (iv) The fourth and the last line explains that the NameError exception has be en ra because of the undefined variable num3. seg ‘Thus, from the above example, we can say that the exception NameError usually contributes a result of: a * Undefined variable + Amisspelled variable or function name * Missed quotation mark or closing parenthesis (b) TypeError: This type of error is raised when an operation or function is attempted that is invalid for the specified data type. This type of exception may result from any of the following possible reasons: + When we are trying to use a value improperly. For exampl with something other than an integer. * There is a mismatch between the items in a format string and the items Passed for conversion. This can happen if either the number of items does not match or an invalid conversion is called for. indexing a string, list or tuple * We are passing the wrong number of arguments to a function or method. For methods, look at the method definition and check that the first parameter is self. Then look at the method invocation; make sure we are invoking the method on an object with the right type and providing the other arguments correctly. #Adding two numbers numl = 10 num2 = 20 print ("sum of two numbers="+ num1+num2) Output: Traceback (most recent call last)? File "Cc: /Users/User4/appData/Local/Programs/Python/Py thon311/3.9 1.py", line 5, in
print("sum of two numbers="+ num1+num2) TypeError: can only concatenate str (not "int") to str >>> Fig. 3.6(b): TypeError exception value In the error message (Fig. 3.6(b)), the error is in line 3 within the print() statement as the te of num1+num2 is used in integer (int) which should be in string type (str) and, hence, ‘TypeError exception gets raised. x7 Computer Science with Pytho™” — &“a oO @ © valueError: This exception is raised when we try to perform an operation on an incorrect tYPS of value. In other words, when a built-in operati ment that has of tight type but an inappropriate te a.crerstion or function receives an argu! ppplage = int (input ("Enter your age sj)” Enter your age: eia ” See | ‘Traceback (most recent nt call last): File “
", line 1, in cmodute> | age = dntcs 1 our ti |, mput ("Enter your age :“)) wekrror: inva’ =) 4id Literal for int() with base 10: * #2! Fig. 3.6(c): Valuetrror exception zeroDivisionError: This exception is raised when division or modulo by zero takes place for all numeric types. It occurs when in division operation, denominator is inputted as Zero. yeinding inverse of a number itm = eval (input ("enter a number™)) rev_pun=i/num feint("inverse of a nuxber=", rev_num) Output: lsraceback (most secent call tact) File "C:/Users/User4/AppData/Local, in311/3.10_1-py", line 3, in ear ee amet aor rev_num=i/num zeroDivisionzrror: division by zero >>| Fig. 3.6(d): ZeroDivisionError exception AttributeError: This exception is raised when an object does not find an attribute. We are trying to access an attribute or method that does not exist. Check the spelling! We can use dir to list the attributes that do exist. If an AttributeError indicates that an object has None Type, that means that it is None. One common cause is forgetting to return a value from a function; if we get to the end of 3 function without hitting a return statement, it returns None. Another common cause is using the result from a list method, like sort, which returns None. Also, this error can occur when we are using a method not associated with a particular object like list holding integer values and we are trying to use append() method which is not acceptable and, hence, AttributeError exception is thrown as shown in Fig. 3.6(e)). fatdet = 0 for 4 in range(10): aList.append(1) lprine(atdst{101) Output: ‘Traceback (most recent call last): Tile "C:/Users/User4/AppData/Local/Programs/Python/Pytho lna11/3.11_1-py", line 3, in
alist. append (i) lattributerrror: ‘int’ object has no attribute ‘append’ b>>>| Fig. 3.6(e): AttributeError exception ton Hane ee, of(f) KeyError: This type of error occurs when we are trying to access an element of a qi (g)_ IndexError: The index we are using to access a list, string, or tuple is greater than j ™~ Iti using a key that the dictionary does not contain. Onan, ) at ‘one’, 21 'Two', 3: >>>|print (digits rive'}) Traceback (mont recent call last): | File "
", line 1, in
| print (digits ['Five'}) | KeyError: ‘Five! | J “Fig. 3.6(f): KeyError exception ts Ie minus one, This exception is raised when an index is not found in a sequence. In other et Bt it occurs whenever we try to access an index that is out of a valid range. ds rds ['rea’, iue'] ‘green’, >>>/eolors [4] Traceback (most recent call last): File "
", line 1, in
colors [4] IndexError: list index out of range Fig. 3.6(g): Index€rror exception (h) oError: This exception occurs whenever there is an error related to input/output such 5, @ opening a file that does not exist, trying to delete a file in use, removing USB while readin, operation is going on. In all these situations, where some interrupt occurs in input/outpy: operation, I0Error exception is raised. >5>/£ = open(' passwordFile. txt") |fraceback (most recent call last): | File "“
", line 1, in
| £ = open('passwordFile.txt') FileNotFoundError: [Errno 2] No such file or directory: "passwordFile.tzt: >>>) Fig. 3.6(h): [OError exception IndentationError: Indentation is one of the important factors that should be taken into account while writing Python programs. Each statement written in the block should have the same indentation level. In case of violation of this rule, it results in Indentation error. This type of exception is raised due to incorrect indentation while typing if-else statements orin looping statements (compound statements) or even in defining user-defined functions/modules. >>>|limit = 5 | >>>|for num in range (limit): | ~ +> Brint (num) Syntaxerror: expected an indented block after 'for' statement on line 1 >>>| Fig. 3.6(I): Indentation exception 3.4 HANDLING EXCEPTIONS IN PYTHON An exception is an error that occurs while a program is running, causing the program to abruptly halt. Errors that occur at execution time are the exceptions. These errors disrupt the flow of the program at run-time by terminating the execution at the point of occurrence of the error. a — & - ——
Beeeute thi eas wing > is exception Ro match is found Syntax: We do our operations here except Exception (Name) - I: If there is exception-I, then execute this block. except Exception (Name) - II: If there is exception-II, then execute this block. except Exception (Name) - III: If there is exception III, then execute this block. except: If there are no exceptions with the specified name given above, then execute this block. Example: [Wividing two numbers num=0 while numt=100: try: numl=eval (input num2=eval (input num3=numi //num2 Print("me quotient tem") numa), e ei print ("Variable sen | SRSeRE Namezrror: Print (\varise (rpivision by Zero not defined") |__except: print("an error has occured") wenter dividend ")) "enter divisor “)) — epon Handing xen, GY me meOutput: _ jenter dividend 25 jenter divisor 5 The quotiont 4e= 5 ‘dividend 76 lznter divisor 0 Division by Zero not defined Enter dividend 78 Enter divisor 5 Ime quotient 4s Enter dividend b Variable not present Enter dividend 34 Enter divisor 2 [me quotient s= 17 [Enter dividend 100 Enter divisor 6 The quotient 4s 15 16 >>>! Fig. 3.14: try with multiple except blocks Explanation: In this program when a user enters 0 as divisor, error "Division by zero not defined” occurs. When the user enters ‘a’ as the dividend, error “Variable not present” occurs. Learning Tip: Any suite of valid statements can be given in an except clause, Method 4: try...except with finally block The finally block is called clean-up or termination clause because it is executed under al circumstances, i, a “finally” block is always executed irrespective of whether an exception has occurred in a try block or not. In order to implement some sort of action to clean up after executing our code, Python enables us to do so using the finally clause. there Is an exception &a--—— a Computer Science with Python-X!!Syntax: try: We do our operations here except Exception-I: If there is exception-I, then execute this block. except Exception-Ii If there is exception-II, then execute this block. else: If there is no exceptions, then execute this block. finally: Always executed. Exampl [apividing two numbers nun=0 while num!=100: try? numi=eval(input ("Enter dividend ")) num2seval(input ("Enter divisor ")) num3=numi //num2 print("The quotient is= ", num3) except NameError: print ("Variable not present") except ZeroDivisionError: print ("Division by Zero not defined") except: print("an error has occured") finally: print ("done!!!!") Output: Enter dividend 25 Enter divisor 5 The quotient is= 5 ldone!! 1 lenter dividend 18 lznter divisor 0 Division by Zéro not defined idonet ttt enter dividend a variable not present ldonet 111 lunter dividend 100 lunter divisor 4 lThe quotient is= 25 ldonet ttt b>oo| Fig. 3.16: try..except with finally clause Explanation: whether exception occurs or not. So done! == Exception Handling In this program the print statement given in the finally clause is always executed irrespective of ! gets displayed after every iteration of while loop. @—i—preerene 1S)iNa DAt) v raise allows us to throw an exception manually. Runtime errors occur during the execution of a program. Irregular unexpected situations occurring during runtime are called Exceptions. Exceptions may occur even if the program Is free from all types of errors. In the try clause, all statements are executed until an exception Is encountered. except is used to catch and handle the exception(s) that are encountered in the try clause. else lets us code sections that should run only when no exceptions are encountered in the try clause, Finoity enables us to execute sections of code that should always run, with or without any previously encounterey exceptions. vv vy . vv OBJECTIVE TYPE QUESTIONS 1. Fill in the blanks. (a) On encountering a .. are removed by the user. (b) When a number is divided by 0, error is raised. © is a Python object that represents an error. @) . error is raised when a local or global variable is not defined. (e) The.. block holds the code to be run and checked for any error, if exists. . error, the interpreter does not execute the program unless these errors 2. State whether the following statements are True or False. (a) Value€rror occurs due to wrong indentation in a program. {b) Exception and error are the same objects. (c) Exceptions are caught using try block. {d) The order of exception handling in Python is try, followed by except, and then finally. {e) Catch is a part of exception handling. 3. Multiple Choice Questions (MCQs) (a) The errors encountered when a user violates the syntax of a programming language while writing a code are termed as : (i) Compile time error (ii) Logical error (iil) Runtime error (iv) Exception (b) An interrupt or forced disruption that occurs when a program is run or executed is termed 35 (i) Compile time error (ii) Exception (iii) Runtime error (iv) Logical error (c)_ Which of the following keywords are not specific to exception handling? (i) try (i) except (iii) else (iv) finally (d) Which block is a mandatory block in exception handling process? () ty (il) except (ili) finally (iv) else {e) Forced exceptions are indicated using which of the following keywords? @ ty (li) except (tii) finatty {iv) raise - Computer Science with Python-X! —~i— &AOS 4, Define an exception. sans, Exception in general refers to some contradictory or unusual situation which can be encountered unexpectedly while executing 9 Program. Inother words, an exception isan error that happens during execution of a program. 2, How is an exception handled in a Python program? ‘ans, We can handle exceptions using the try...except statement. We basically put our usual statements within the try-block and put all our error handlers in the except-block. The except block indicates the action to take when the given type of exception is raised within the corresponding try block. If no exception is raised, execution owes normally and the except block skipped. 3, How many else clauses can be added into a try...except block? ‘ans. Only one 4, Why finally clause is called as cleanup? ns. A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. When an exception has occurred in the try clause and has not been handled by an except clause (or it has occurred in an except or else clause}, it is re-raised after the finally clause has been executed. 5, How many except clauses can be included in a try block? ‘ans. Any number of except clauses 6. What happens when an abnormal condition happens in a program? ‘Ans, When an abnormal condition to the program flow has been detected, an instance of an exception object is created. It is then “thrown” or “raised” to code that will catch it. 7. What type of error it will produce when we type: Result = “Python” + 10 Name the error and error message. Ans. The error is: TypeError The error message i ‘an't convert ‘int’ object to str implicitly What type of error it will produce when we typ: while True print("Hello world”) ‘Ans. The error is: Syntax€rror: invalid syntax 9, What type of error it will produce when we type: ‘+8 ‘Ans. The error is: TypeError 10. What will be the output of the following program? x,y, a= 5,0,None print ("a") try: print ( a=x/y print ("c") except: print print print (a The output zy fea Ans.11, What output the Python code shall produce? Justify your answer. x=5 yoo print ('A") try: print ('B') A= x/y print ('C') except ZeroDivisionError: print ('F*) except : print ('D') Ans. The code will produce the following output: A B F Explanation: The statement print ‘A’ will produce A. The first statement of the try block is print ‘B” and will produce B. The next line in try block is a = x/y which generates a ZeroDivisionError because, x=5 and y= has zero as the denominator. So, the try block will follow the except. ZeroDivisionError: with statement print ‘F’ and will produce F. 12. What will be the output of the following Python code? Explain the try and except used in the code, FB, Expression B=6 print ("One") try: print ("Two") X=8/A z print ('Three') except ZeroDivisionError: print (B*2) print ('Four') except: print (b*3) print ('Five') Ans. The output is: one Two 12 Four In the given code, all the statements within the t occurs. If a division expression has zero as the denominator, this causes a Zero and the except block indicates the action to take when the given type of exception is raised within the corresponding try block. 13. Explain try..except...else with the help of an example which raises an error when the denominator Is 280 while dividing X by Y and displays the quotient otherwise. Ans. #Function to demonstrate try...except...else block x = int (input ("Enter first number: ")) y = int (input ("Enter second number: ")) print ("Two nos .are: ", x,y) try: ry-block will be executed smoothly till ZeroDivisionError isionError to be raised result = x/y . We A — & A ‘Computer Science with Python-X!y except ZeroDivisionError: print ("cannot divide by zer cise? print ("The result is:” ") the above program cod Lael ram From ‘ode, the except block indicates the action to be taken when the given type ception is raised within the cor of fe corresponding try block. When a division expression has zero as the Genominator, f-e., Y= 0, then this causes a deneites only i 0 exception i raised In the s ZeroDtdslontrror to be raised, Otherwise, the else block ASSERTION AND REASONING BASED QUESTIONS. wing questions contai eae contain two statements: Assertion and Reasoning. Each question has four choices— (a,c (i, s correct. In the light of these statements, choose the most appropriate option- {Both Aand R are true and Ris the correct tion of A. {ij Both Aand R are true but Ris not the correct explanation of A. {ij Ais true but R is false. {a Ais false but Ris true, 1. assertion (A): Exception handling handles all types of errors and exceptions. Reasoning (R): Exception handling is responsible for handling anomalous situations during the execution of 3 program. 2. assertion (A): Exception handling code is separate from normal code. Reasoning (R): Program logic is different while exception handling code uses specific keywords to handle exceptions. 3. Assertion (A): Exception handling code is clear and block based in Python. Reasoning (R): The code where unexpected runtime exception may occur is separate from the code where the action takes place when an exception occurs. ‘4 assertion (A): No matter what exception occurs, you can always make sure that some common action takes place for all types of exceptions. Reasoning (R): The finally block contains the code that must execute. Ans. 1. (i) 2.(i) 3. (1) 4.(i) UNSOLVED QUESTIONS +L. What all can be the possible outputs of the following code? def myfunc (x=None) ? result ="" if x is None: result = "No argument given" elif x == 0: result = "Zero" elif 0
You might also like
Supplement (CS XII) 2023-24 For Web
PDF
86% (7)
Supplement (CS XII) 2023-24 For Web
24 pages
CS Project
PDF
100% (1)
CS Project
30 pages
Preeri Arora Chapter5 First Year
PDF
50% (2)
Preeri Arora Chapter5 First Year
31 pages
Solution Revision Tour Worksheet PDF
PDF
100% (3)
Solution Revision Tour Worksheet PDF
10 pages
Class 12th - QuestionBank - ComputerScience
PDF
No ratings yet
Class 12th - QuestionBank - ComputerScience
184 pages
CS - Practise Papers - Xi
PDF
100% (2)
CS - Practise Papers - Xi
39 pages
Class: Xi Session: 2022-23 Computer Science (083) Practice Paper-1 (Theory) Maximummarks:70 Time Allowed: 3 Hrs General Instructions
PDF
100% (1)
Class: Xi Session: 2022-23 Computer Science (083) Practice Paper-1 (Theory) Maximummarks:70 Time Allowed: 3 Hrs General Instructions
48 pages
Computer Science CLS 12
PDF
100% (1)
Computer Science CLS 12
10 pages
Python Viva Questions For Class 12 Important For Practical Exam
PDF
100% (1)
Python Viva Questions For Class 12 Important For Practical Exam
7 pages
Working With Functions
PDF
No ratings yet
Working With Functions
34 pages
Practical File: Program 1: Program To Enter Two Numbers and Print The Arithmetic Operations Like +,-,, /, // and %
PDF
No ratings yet
Practical File: Program 1: Program To Enter Two Numbers and Print The Arithmetic Operations Like +,-,, /, // and %
36 pages
Chapter-2 Function
PDF
100% (1)
Chapter-2 Function
40 pages
Grade 12 CS Practice Material 2023-24
PDF
100% (1)
Grade 12 CS Practice Material 2023-24
217 pages
Cs (File Handling) Important
PDF
No ratings yet
Cs (File Handling) Important
12 pages
Art Integrated Project Computer Science
PDF
No ratings yet
Art Integrated Project Computer Science
15 pages
Question Bank Class Xi Cs-4
PDF
No ratings yet
Question Bank Class Xi Cs-4
20 pages
Working With Functions Sumita Arora MCQ
PDF
67% (3)
Working With Functions Sumita Arora MCQ
7 pages
11th Dictionary Type B Sumita Arora
PDF
100% (1)
11th Dictionary Type B Sumita Arora
15 pages
Q1) Input A Welcome Message and Display It. Code: Python Program
PDF
No ratings yet
Q1) Input A Welcome Message and Display It. Code: Python Program
12 pages
Assignment Networking-1
PDF
No ratings yet
Assignment Networking-1
16 pages
Computer Science Practical
PDF
No ratings yet
Computer Science Practical
43 pages
Sample Practical File XI CS
PDF
100% (1)
Sample Practical File XI CS
5 pages
Class Xii Computer Science (Question Bank - MLL)
PDF
No ratings yet
Class Xii Computer Science (Question Bank - MLL)
40 pages
Class-12 File Handling Question and Answer
PDF
No ratings yet
Class-12 File Handling Question and Answer
19 pages
Preboard2 - MS CS
PDF
No ratings yet
Preboard2 - MS CS
14 pages
Python Strings - Notes - Class Xi
PDF
No ratings yet
Python Strings - Notes - Class Xi
5 pages
Exception Handling (CS)
PDF
No ratings yet
Exception Handling (CS)
23 pages
CS 2024 QP Practical
PDF
No ratings yet
CS 2024 QP Practical
6 pages
Cs Class 12 Codes
PDF
No ratings yet
Cs Class 12 Codes
28 pages
Function Practice Questions
PDF
No ratings yet
Function Practice Questions
16 pages
Strings Class 11
PDF
No ratings yet
Strings Class 11
18 pages
Class XI Sample Exam Paper CS
PDF
100% (1)
Class XI Sample Exam Paper CS
7 pages
Pyqs of Data Structure - Stack For More Such Type of Questions and Detailed Video Explanation, Visit The Link
PDF
100% (1)
Pyqs of Data Structure - Stack For More Such Type of Questions and Detailed Video Explanation, Visit The Link
6 pages
CBSE Class 12 Computer Science Compartment Answer Key
PDF
No ratings yet
CBSE Class 12 Computer Science Compartment Answer Key
24 pages
Chapter 3 - Working With Functions
PDF
100% (1)
Chapter 3 - Working With Functions
6 pages
Python Revision Tour - Solutions of Computer Science With Python by Sumita Arora For Class 12 CBSE & NCERT - KnowledgeBoat
PDF
No ratings yet
Python Revision Tour - Solutions of Computer Science With Python by Sumita Arora For Class 12 CBSE & NCERT - KnowledgeBoat
44 pages
Chapter-13-Table Creation and Data Manipulation Commands - NOTES
PDF
No ratings yet
Chapter-13-Table Creation and Data Manipulation Commands - NOTES
8 pages
Class 12 Full Syllabus Notes
PDF
100% (1)
Class 12 Full Syllabus Notes
74 pages
12 CS RevisionPapers2025
PDF
No ratings yet
12 CS RevisionPapers2025
86 pages
Binary File Exam Based Questions
PDF
100% (1)
Binary File Exam Based Questions
10 pages
BINARY FILE Question Bank Solutions
PDF
No ratings yet
BINARY FILE Question Bank Solutions
10 pages
Marking Scheme Computer Science 083
PDF
No ratings yet
Marking Scheme Computer Science 083
26 pages
CS Prctical File Class XI
PDF
100% (2)
CS Prctical File Class XI
31 pages
Data Communication Notes Class 12 CS by Nitin Paliwal
PDF
100% (2)
Data Communication Notes Class 12 CS by Nitin Paliwal
7 pages
MS CS Agra PB1 2024-25
PDF
No ratings yet
MS CS Agra PB1 2024-25
11 pages
12 CS PB1 CHN MS
PDF
No ratings yet
12 CS PB1 CHN MS
5 pages
Class 12 Cs Investigatory Project
PDF
No ratings yet
Class 12 Cs Investigatory Project
24 pages
ComputerScience-SQP Set5-MS
PDF
No ratings yet
ComputerScience-SQP Set5-MS
13 pages
Exception Handing
PDF
No ratings yet
Exception Handing
5 pages
12th Computer Science Practical User Manual 2024 2025
PDF
No ratings yet
12th Computer Science Practical User Manual 2024 2025
54 pages
ComputerScience SQP Set3 MS
PDF
No ratings yet
ComputerScience SQP Set3 MS
12 pages
Answer Key For HF
PDF
No ratings yet
Answer Key For HF
6 pages
Random Output Questions
PDF
100% (3)
Random Output Questions
4 pages
ComputerScience SQP Set2 MS
PDF
No ratings yet
ComputerScience SQP Set2 MS
12 pages
CS-MS-1 241107 173716
PDF
100% (2)
CS-MS-1 241107 173716
21 pages
Error Handling
PDF
No ratings yet
Error Handling
4 pages
Society Law and Ethics Class 11 Sumita Arora Notes
PDF
No ratings yet
Society Law and Ethics Class 11 Sumita Arora Notes
5 pages
Exception Handling
PDF
No ratings yet
Exception Handling
3 pages
Exception Handling
PDF
No ratings yet
Exception Handling
3 pages
Python Programming Unit 3
PDF
No ratings yet
Python Programming Unit 3
36 pages