You are on page 1of 22
4,1 INTRODUCTION art from computer programs that we code, an exception or error or unusual condition can occur ‘nin our daily life. Consider a real-life scenario—we leave our house for office by car. On the way, bursts and we are forced to stop the car and replace the tyre. In this scenario, the punctured js the exception that has occurred unexpectedly. In such a situation, we are required to carry slong 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 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 errors get reported to the user, sometimes they get logged to a file, etc, It depends on the Sometimes an application can recover from an error and still provide normal, expected behaviour, gramming also. specific error and the application. The same is applicable in the field of computer pr 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 inderstand that programs have to deal with these errors. process of finding errors in a program is termed as Debugging eto errors, a program may not execute or may generate wrong output. So, it becomes necessary find and remove errors for successful execution of a program. Errors in Python are classified into three types: Syntax Error ical Error (b) Run-time Error —_ A) 3.2.1 Syntax Error ‘ A syntax error is an error in the syntax of a sequence of characters OF tokens thay be written in a particular programming language. These types of errors are Benera, Neng violate the syntax or, in other words, the grammatical rules of a programming lity teq whet eal Srrors are the most common type of errors and are easily traceable. Some examph age Oy, syntax errors are: ®S of nyt 1 hy 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 mess, what is wrong in the program is displayed. Re boy For example, >>leine ‘Hello world’ \syntaxzrror: Missing parentheses in call to ‘print’. Did you wean print (<3? | >>> Fig. 3.1: Syntax Error: Invalid Syntax - The given statement is an example of syntax error as it violates the language protoco} by not Parentheses() with the print() function. So, the corrected statement should be: Ahvng >>> print (‘Hello world') Hello world However, some syntactical errors are quite hard to find. Python is case-sensitive, so we may wrong case for a variable and find out that the variable isn’t quite working as we though’, ay ‘Ould, For example, Traceback (most recent call last): File "", line 1, in | Print (4+5) MameError: name ‘Print’ is not defined. pid you mean: ‘print’? >>> . | 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 (4+5) 3 Most syntactical errors occur at the time of program execution and the interpreter points then out for us. Fixing the error is made easy because the interpreter generally tells us what to fix with considerable accuracy. errors that occur due to incorrect format of a Python statement. They occur while to machine language and before being executed. a xn" Computer Science with Pytnor” wo” 4 -e examples of syntax errors are shown below in Fig. 3.2. = Oe Fg 227 gyntaxError: closing = <= Betatement 2 lopening parenthesis (1 es does not match if Tunmcror! incomplete La Mstatement2 syotaxirror: incompists inpat Fe eer miazing pon Mstatement 3 Did you mean print(. 3" ‘theses in call to ‘print’ ppo|tet = (475 6} Jeretamecenes Aneatan opacee statement 4 es 4 in range (19) eee ee ee is Statement 5 a rn es statement on line 1 dented block after >>>, Fig. 3.2: Other types of Syntax Errors understand the reason behind the occurrence of each error given in the above example. set eanement 1 generates syntax error because of improper closing bracket (square bracket instead Pe varenthesis)- statement 2 generates syntax error because of missing colon (:) after ‘if’ keyword to end if 2 Srrement. 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 * geclaration. «, statement 5 generates syntax error because of improper indentation. 322 Run-time Error ‘run-time error occurs after Python interpreter interprets the code we write and the computer tegins 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 an error (exception) dialog box or when the user complains about erroneous output. It usually results jnabnormal program termination during execution. For example, eee >>>]i0* (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 a In Python, such unusual situations are termed as Exceptions. Exceptions are Usually run Mt 3.2.3 Logical Errors % A logical error/bug (called semantic error) does not stop execution but the Progr incorrectly and produces undesired/wrong output. Since the program interprets’, when logical errors are present in it, it is sometimes difficult to identify these errors, Logical errors are the most difficult to fix. They occur when the program runs Witho, but produces an incorrect result. The error is caused by a mistake in the program's longi: ™hiy Set an error message because no syntax or run-time error has occurred, «We wont am eSsfy he stay a Some examples of logical errors are: + Using the wrong variable name for calculations. * Using integer division or modulus operator in place of division operator * Giving wrong operator precedence. We will have to find the problem on our own by reviewing all the relevant parts of th e For example, if we wish to find the average of two numbers, 10 and 12, and we write the cont Code, 10+ 12, it will run successfully and produce the result 16, which is wrong. The correct Code find the average should have been (10 + 12)/2 to get the output as 11. For example, #llustrating Logical Error = X= float (input(Enter a number: *)) ¥ = float(input (‘Enter a munbe; 2 = xty/2 Print ('The average of the to numbers you have entered ‘s:',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 ea not give the right answer; this is known as logical error. Enter a number: 3 4 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 x = float(input(*znter a number: ')) ¥ © float(input('znter a number: ‘) a = (xty)/2 Print (‘The average of the two numbers you have entered is ch Pier Computer Science wt ur é on? 1 is exception Handling 24 me ing language that we work with vero erent to handle an error that ‘oe mee program execution. Likewise, as SP uring ° ‘complete mechanism for ys des a ee a en it occurs. This mechanism ai flit ception Handling. ane echnically, an error is termed as jyctP0™ exception is an error that happens poe? cecution of a program. Ifan exception us ea the program is terminated. cal 2 i i es ception can be described as an interrupt or an event triggered during the normal flow ‘thus Becca of a program, which is to be handled carefully. ox ofthe nan except Feeeption and Fig, 3.4: An Exception jon is raised on account of some error, the program must contain code to catch this andle it properly. (cw Gaception efers to an abnormal condition that arises during the program execution. « discuss some important terms related to Exception Handling: tet (i) Traceback: The lengthy error message that is shown when an exception occurs during the program run is called a traceback. The traceback isa 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. (ii) ‘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 Excep' n 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. detected during execution are called exceptions. In other words, an exception is an error that program is running. They indicate something unusual has happened in the program. RD EXCEPTIONS IN PYTHON us a way to handle exceptions so that the script does not terminate but executes de when an exception occurs. This concept is called Exception Handling. be addressed by its name. Python has some built-in exception names for common juired, a programmer can also define his/her own exceptions. ~FUN _ Mand say yh PFORTaM. we say that exception was ratseq eg > weal with It and say it is handled’ Ssesht And the code writen to hang: ty ial tion handler. 18 lang For handling exceptional situations Python provides— 7 raise statement to 2. try... except Exceptions ii raise exception in the program. ny theg geor catching and handling errors (which wil be taken tis in Python’ section) Mana raise Statement: . Peak statement allows the program to force a specified exceptio Python automatically raises an exception when it encours M tO occur a Program execution. Once ers an error ting an ception rasan, es up tye un either handle it using try/except statement or let it propagate further. netion Syntax: raise [exception name [, message/argument][, traceback]] Here, * exception name is the type of error, wh ich can be string, exception class. class or object. It is an instance g argument is the value/parameter error. We can also give our own me: if (m>5): Eaise Exception('x should not exceed 5°) | Output: Traceback (most recent call last)? File "C:/Users/User4/appData/Local/Programs/P ython/Python311/3.7_1.py", line 3, in print("sum of two numbers=", num1+num3) name ‘num3' is not defined. Did ‘numi '? Fig. 3.6(a): NameError exception . — , The given screenshot gives the description about NameError, which consists of (i) Traceback, which describes a list of the functions which were running ang ig Play, ay the time of occurrence of the exception. (ii) The second line defines the path where in the program the exception has oc, which is prog_excep2.py in the given example along wig ig the name of the program, number, i (iii) The third line shows the actual place of error, i.e., the statement in which, the ep occurred which is print() method. "Or, (iv) The fourth and the last line explains that the NameError exception has been », gy because of the undefined variable num3. Thus, from the above example, we can say that the exception NameEror usually contr, a result of: tes ay + Undefined variable + A misspelled 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 th, Lis invalid for the specified data type. This type of exception may result from any of the ay, possible reasons: wing + When we are trying to use a value improperly. For example: indexing. a string list ory with something other than an integer. ‘ple items Passed fo, There is a mismatch between the items in a format string and the nv conversion. This can happen if either the number of items does not match or an, conversion is called for. + We are passing the wrong number of arguments to a function or method. For methog, look at the method definition and check that the first parameter is self. Then look a ty, method invocation; make sure we are invoking the method on an object with the gh type and providing the other arguments correctly. ‘WAdding two numbers - numi = 10 (num2 = 20 Print ("sum of two numbers="+ numi+num2) ‘Traceback (most recent call last) | File "c:/Users/User4/appData/Local/Programs/Python/Py /tnon311/3.9 1.py", line 5, in | | print ("sum of two numbers="+ numi+num2) | |mypekrror: can only concatenate str (not "int") to str >>>, Fig. 3.6(b): TypeError exception In the error message (Fig. 3.6(b)), the error is in line 3 within the print() statement as the vall® of num1+num2 is used in integer (int) which should be in string type (str) and, hence, te Error exception gets raised. as. otha-Mt ‘this exception is raised when we try to perform an operation on an incorrect type ‘er words, when a built-in operation or function receives an argument that has ut an inappropriate value. “unter your age :")) Pele nto ck (most recent call last): MetrceysislG>", line 1, in ?) Fig. 3.6(c): ValueError exception sionError: This exception is raised when division or modulo by zero takes place for @ iil ‘numeric types. It occurs when in division operation, denominator is inputted as zero of a number=", rev_num) output: Secaback (most recent call test) ‘File "C:/Users/User4/AppData/Local/Programs/Python/Pytho 311/3-10_1.py", line 3, in ‘rev_num=1/num geropivisionError: 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. Ifan 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 a 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)). atist = 0 ] for 4 in range(10): auist. append (i) Print(atist[10]) Output: (most recent call last): "c: /Users/User4/AppData/Local/Programs/Python/Pytho n311/3.11 1.py", line 3, in st append (i) ror: ‘int’ object has no attribute ‘append’ Fig. 3.6(e): AttributeError exception -_ aK — (9). Keykrror: This type of error occurs when we are trying to access an element oy a using a key that the dictionary does not contain. ny >>>]aigits = (0:'zero', 1: ‘One’, 2: ‘Two’, 3: >>> print (digdte[ 'Five' 1) ‘Traceback (most recent call last): File “", line 1, in print (digits['Five']) | Keyzrror: 'Five' >>>| Fig. 3.6(f): KeyError exception (g)_IndexError: The index we are using to access a list, string, or tuple is greater thay ig minus one. This exception is raised when an index fs not found in a sequence. tn gino it occurs whenever we try to access an index that is out of a valid range. or >>>leolors = [‘red', ‘green’, raceback (most recent call 1: File "“", line 1, colors[4) IndexError: list index out of range Fig. 3.6(g): IndexError exception (h) l0Error: This exception occurs whenever there is an error related to input/output ‘pening a file that does not exist, trying to delete a file in use, removing USB while rea operation is going on. In all these situations, where some interrupt occurs in j operation, 1OError exception is raised. Such ag Arte MPUL/outpy, SS>[f = open(‘passwordFile. txt") Traceback (most recent call last): i File "“", line 1, in | £ = open('passwordFile.txt') riteNotFoundError: [Errno 2] No such file or directory: ‘passwordriie. ext)| >>) Fig. 3.6(h): |OError exception @ _IndentationError: Indentation is one of the important factors that should be taken into accour while writing Python programs. Each statement written in the block should have the sane 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 Tooping statements (compound statements) or even in defining user-defined functions/modules >>>/limit = 5 | >>>|for num in range (limit): .-. rint (num) SyntaxError: expected an indented block after ‘for' statement on line 1 >>>| | Fig. 3.6(i): Indentation exception 3.4 HANDLING EXCEPTIONS IN PYTHON : . th error that occurs while a program is running, causing the program to ae cur at execution time are the exceptions. These errors disrupt the flow ie by terminating the execution at the point of occurrence of the error: cy i Computer Science with python weer that whenever an exception occurs, a Traceback (already explained in the previous js aisplayed which includes error name, its description and the point of occurrence Such as line number, ing in Python involves the following steps: foot the moment an error occurs the state of execution of the program is saved a flow of the program is interrupted (stopped for a moment). function or piece of code known as exception handler is executed. + AsPer gn of the program is resumed with the previously saved data. r handling is called exception handling. ig. 3.7: Exception Handling in Python can use the try-except statement to gracefully handle exceptions. Here are the different Wfhods for handling exceptions in Python method 1: try and except block she try and except block in Python is used to catch and handle txceptions. Python executes code following the try statement jsa*normal” part of the program. The code that follows except statement is the program's response to any exceptions in the preceding try clause, ifwe have some suspicious code that may raise an exception, wwe can defend our program by placing the suspicious code in a try: block When we use try..except block in the script and an error is encountered, a try block code execution {s stopped and transferred down to the except block Learning Tip: Python provides three keywords to deal with exceptions: * raise ety + except Exception handling has two steps = Raising or Throwing = Catching Co} except | Execute this code when there is an exception Fig. 3.8: Using try and except block We do our operations here except: If there is an exception, then execute this block. CO — a, --{i,- WIth reference to Fig. 1.6(a), the program was weltten to calculate humbers, with an error (Namelirror) in the print() statement In the absence fy exception handling mechantam, the program terminated abruptly and th This Program can be modified and weitten using try-except DICK 6 that a poy, Provided to the user on the occurrence of any interrupt, L Let Us rewrite Fig. 3.6(a) example using tryexcept bloek. [fading to umber try: mum 0 | mum “20 PELNE (“sum of two numbers=", numi¢numa) Jexceptt PrAnt (“An error has occured") Output: [An @r¥or has occured >> Fig. 3.9: Exception Handling using try...except block Explanation: Iwe compare the output of the example prog Program does not end abruptly but displays an 1m in Fig. 3.6(a) and Fig. 3.9, we find that thy la ror message. Mey As there is an error in the print statement (variable num3 is not declared), execution is stopped and transferred down to the except block. The print stat except block is executed. “UY block coy ent pr ; TAL the Let us take another example to explain try...except block Example: To perform division of two numbers. Wdividing two numbers | numiseval (input num2~eval (input num3=numi//num2 Print ("The quotient is =", nums) except: Print ("An error has occurred") inter dividend") ) ‘Enter divisor")) Enter divisoro An error has occurred Enter divisoré ZeroDivision Exception raised using try except The quotient is = © cause and displaying proper message othe et ter dividend ool (6p Scien wh PYM an exception causes a program to abn Po arr gracefully avoiding an exception ptly halt. For example, look at Fig. 3.10. exal isa” numbers from thy w m gets 00 © user and then divides the first number by the second 8 : ing of the program, hi sample re Gai : peer an exception occurred because the user entered 0 wend ma ppniion an exception because it is mathematically impossible.) rogram does bs 6 le pee ay een abruptly when an error occurs. If we do not use a os in this P a. ee ‘ate when we enter divisor as 0 because division by 0 is scored. But here ‘S error message and continues to execute further. wren code, tne error message does not display the ee SP tirnluple except statements, type of error. To know more about the ‘use try..except clause in the script and an error i So Peiicces ee ‘or is encountered, a try block code execution . try..except with else block eho 217 reelse cause of try statement is used to specify the code which is executed in case no exception occurs: Fig, 3.11: Using try..except with else block Syntax: You do your operations here except Exception: If there is exception, then execute this block earlier (in syntax errors topic), when syntactically correct code runs into an error, throw an exception error. This exception error will crash the program if itis unhandled. ck determines how our program responds to exceptions. Example; while numt=100; try: | Rumiseval (input ("Enter dividend ")) Rum2=eval (input ("Enter divisor ")) num3=numi //num2 Print ("The quotient % except ZeropivisionError: print ("Division by Ze: else: Print ("Execution is normal") ze Print ("Done!!!!") i not defined”) | Output: Enter dividend 12 Enter divisor 3 ‘The quotient is= 4 Execution is normal Done!!! mnter dividend b Variable not present Enter dividend 40 lgnter divisor 0 Division by Zero not defined Enter dividend 100 Enter divisor 5 ‘The quotient is= 20 Execution is normal Done! !!! eee Cd Fig. 3.12: try..except with else block Explanation: In the above example, the else block is executed only when none of the exceptions is executed Whenever an error occurs, the required exception is executed and else block is not executed Method 3: try with multiple except blocks The try statement may have multiple except blocks with Exception Names to handle specific exceptions and one optional except clause. We can give name of the exception along with the except statement. In such a case, at the occurrence of an exception, the script works as follows: * The control is transferred to the corresponding except block handling the exception which his occurred. * If that particular exception (which has occurred) is not specified in any except block, then the is transferred to the except block without any exception name. f the above two cases are met (there is no except clause handling that particulst id there is no except clause without any exception name), then the script terminat® it happens when no try statement is used, et wit Pytho Computer Science un this code there is except (except Exception Name: ) femmion Run this Code when’ ‘no match is found { { { st in Fig, 3.13: try with multiple except blocks We do our operations here except Exception (Name) - I: If there is exception-l, then execute this block. except Exception (Name) - II: If there is exception-Il, 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 numiseval (input ("Enter dividend ")) Rum2seval (input ("Enter divisor ») Rum3=numi //num2 | Print ("The quotient is= ", num3) | Mamefrror: print ("Variable not present") seal eroDivisiongrror: print("Division by Zero not defined") t print("an error has occured") Output: [enter divi (Enter divisor 5 (The quotient is= 5 ‘Enter dividend 76 (Enter divisor 0 Division by Zero not defined ‘Enter dividend 78 ‘Enter divisor 5 |The quotient is= 15 [Enter dividend b \Variable not present Enter dividend 34 ‘Enter divisor 2 |The quotient is= 17 Enter dividend 100 (Enter divisor 6 ‘The quotient is= 16 >>> Fig. 3.14: try with multiple except blocks Explanation: In this program when a user enters 0 as divisor, error "Divi zero not defined” occurs. When the user enters ‘a’ as the dividend, error “Variable not present” occurs. Method 4: try...except with finally block The finally block is called clean-up or termination clause because circumstances, i.e., a “finally” block is always executed irrespective of occurred in a try block or not. In order to implement some sort of action to clean up after executing our code, to do so using the finally clause. Learning Tip, valid statement in an except Clause, — ion by it is executed under whether an exception 'ython enables Execute this code when there is an exception Always run this code. Fig. 3.15: Using try..except with finally block 4 ston #1 We do our operations here Exception-I: if there is exception-l, then execute this block except Exception Il: If there is exception-Il, then execute this block. except else: , If there is no exceptions, then execute this block. finally: Always executed. ample: qpividing two numbers =0 22 saatni00: try? F numiseval(input ("Enter dividend pumgeeval(input ("Enter divisor ")) | nunsenumi / /nun2 print("The quotient is= ", num3) except NameError: print ("Variable not present") | Gxcept ZeroDivisionError: print("Division by Zero not defined") | print ("an error has occured") print ("done!!!!") Nariable not present idone! 111 ~except with finally clause print statement given in the finally clause is always executed irrespective of after every iteration of while loop. occurs or not. So done!!! gets displayed > raise allows us to throw an exception manually. Runtime errors occur during the execution of a program. Irregular unexpected situations occurring during funtime are called Exceptions, Exceptions may occur even ifthe program is free from all types of errors In the try clause, al 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 jn, Pas t {inaly enables us to execute sections of code that should always run, with or without any pe » > > > > > > exceptions. eR] 0 add SS 1. Fill in the blanks. (a) On encountering a error, the interpreter does not execute the program unles, are removed by the user. MIS these (b) When a number is divided by 0, (c) is a Python object that represents an error. (a) 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 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 error is raised. (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 wile are termed as (i) Compile time error (ii) Logical error (iv) Exception uted is ene! (iii), Runtime error (b) An interrupt or forced disruption that occurs when a program is run or exe" (i) Compile time error (ii) Exception Runtime error (iv) Logical error of the following keywords are not specific to exception handling? - (ii) except (iii) else (iv) fir block is a mandatory block in exception handling process? . (ii) except (iii) finally (w) ‘exceptions are indicated using which of the following keywords? ise | (ii) except (ii) finally P Computer science —_ | PSUS pete 2° ‘exception: Belg penal fers some contradic tory or unusual situation which can be encountered unexpectedly red unexpecte program. In other words, an exceptionis an error that happens during execution of ap rds, an exc ee a per 8 sution| ram. 1 1 hile ‘executing ion handled I ss led in a Python program? isan excel handle exceptions using tl a g the try...except statement. We bi /e basically put our Jr usual statements within o eee eyblock and Pur all our eri we : ror handlers in th Ms © except tnenen the en EN eee areal aint eee blo te he es normally and the except icecrreteenl indicates the action tO o UBIoek ekiprats ing try block. If no exception is rl many ese causes C27 be added into a try...except bl ee except block? or 10 iy nally USE called as cleanup? : ways executed bi tinal clause "© fore leaving the t statement, wl many except clauses can be included in a try block? a Cae cept cl he number of except lat! ens when an abnormal condition happens in a program? ‘ance of an exception object is mePgpnormal conaition to the Progra flow has been detected, an ins eprown’” or “raised” to code that will catch It “om it will produce when we type has ses e of error i “python” + 10 7, what tYP' nd error message js: TypeError ‘ressage is: can’t convert ‘int’ object to str implicitly terror it will produce when We type’ int("Hello world”) axerror: invalid syntax i will produce when we ‘YP or it following proe am"? wer 11. What output the Python code shall produce? Justify your ans 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 ‘W will produce A. Explanation: The statement print The first statement of the try block is print :/y which generates a ZeroDi The next line in try block is a has zero as the denominator. So, the try block will follow the except. ‘8! and will produce B. jonError because, x=5 and y=0, Ores, ZeroDivisionError: with statement print ‘F’ and will produce F. 412. What will be the output of the following Python code? Explain the try and except used in the code a=0 Be6 print (‘one') try: print (‘Two') X=8/A 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 try-block will be executed smoothly till ZeroDivisionEra: ‘occurs. If a division expression has zero as the denominator, this causes a ZeroDivision€rror to be raised and the except block indicates the action to take when the given type of exception is raised within he corresponding try block. 13. Explain try..except...else with the help of an example which raises an error when the denominator is while dividing X by Y and displays the quotient otherwise. | Ans. #Function to demonstrate try...except...else block = int (input ("Enter first number: ut ("Enter second number: nos .are: ", x,y) =x/y A ence win Pte Computer Sc yisionError: BerPPhcannot divide By zero") ne result is:", result) et - ys int Es pie rogram cote; the exce5t Bock indcaes the action tobe taken when the gen type is ao Penile aoe, ses When a division expression has zero as the ea ye oDivisionError ev Vain lee inthe ty block, for to be raised. Otherwise, the else block Smeg se wins rd Wem, Ee cue Fo sj oe nly one . In the light of these statements, choose the most appropriate option. (i re true and Ris the correct tion of A, (iq and R f pat Aaa ace true but Rs not the correct explanation of A Aa @ al put Ris false. (iA age but Rs TUS: pi NBA cal Exception handling handles all types of errors and exceptions assertion Ue . excenti ling is 1 ng (RI: xcention handling is responsible for handling anomalous situations during the execution of won 2 Hion (A): peasorne (| exceptions: a. assertion (A): Exception handling code is clear and block based in Python. Asatfng (The code where unexpected runtime exception may orci separate from the code where feastjon takes place when an exception occurs, s.asserin (A No matter what exceptlon occurs, YOu can always make sure that some common action takes fae for all types of exceptions aang (R): The finaly block contains the code that must execute ws) 20 3.(i) ati) Exception handling code is separate from normal code. «program logic is different while exception handling code uses specific keywords to handle UNSOLVED QUESTIONS 4 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 = resul Zero" elif 0< x <-3: result = "x is between 0 and 3" else: © Fesult = "x is more than 3" teturn result ES ——_ © x A tl —. the followin . {b) Name€rror 2. BR the situation(s) in whi ‘ cae (a) Typeerror 3. Name three run-time errors that Occur ‘during Python program execution, nan error and exception? ple code to illustrate it, ‘4. What is the difference betwee’ tion in Python? Write sam 5, How can you handle an exce' 6. name some common built-in exceptions IP Python. 7. What does the finally clause produce In 3 €Y-- except block? 8. Write syntax of raise statement. 9. Differentiate between 1OError and IndexErr0r- 10. show how to modify the following code'so that an e770" 's printed if the number conversig, val = input ("Enter a number") IS ng pval = int (val) ww and fill in the blanks with appropriate error types: 11. Consider the code given belo * 1oop=1 while loop try: Pe rcinpietsntemchetizst number ‘enter the second number: ') a) b= int (input ( quotient = a/b ‘wprror: Please enter only numbers") except print ( except : Second number should not be zero") print ("\n Error: Check the date typen) except print ("\n Unsupported operatio: else: print ("Great") finally: print ("Program execution completed") 4) loop = int (input ("Press 1 to try again continue

You might also like