[go: up one dir, main page]

0% found this document useful (0 votes)
95 views23 pages

Exception Handling (CS)

Class 12th Cbse Python Except Handling Supplementary PDF.

Uploaded by

arjun37925112
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)
95 views23 pages

Exception Handling (CS)

Class 12th Cbse Python Except Handling Supplementary PDF.

Uploaded by

arjun37925112
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
You are on page 1/ 23
Exception Handling 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—you leave your house for office by car. On the way, the tyre bursts and you 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 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. ERRORS IN PYTHON AND DEBUGGING Most application codes written for developing applications have errors in them. When your 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 toebrors,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: RTC ante fa) § (b) R © L Syntax Assynt be wri violate errors syntax The g giving Howe the w itwou For es (a) Syntax Error (b) Run-time Error (©) Logical Error Syntax Error A syntax error is an error in the syntax of a sequence of characters or tokens that is intended to be written in a particular programming language. These types of errors are generated when we violate the syntax or, in other words, the grammatical rules of a programming language. Syntax errors are the most common type of errors and are easily traceable. Some examples of Python i 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 about what is wrong in the program is displayed. For example, ie tse aly Ope z python 3.6.5 (V3.6.5:f59c0932b4, var 28 2018, 16:07: °| 46) [sc v.1900 32 bit (inte1)} on win32 type "copyright", “credits” or "License()" for more information. >> print. ‘dello worlel] Syntextrzori Missing parentheses in call to ‘print'. Did you mean print (‘Hello worié*)? hae its Fig. 1: Syntax Error Invalid 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: >>> print (‘Hello world") Hello world However, some syntactical errors are quite hard to find. Python is case-sensitive, so you may use the wrong case for a variable and find out that the variable isn’t quite working as you thought it would. For example, a 5 python 3.6.5. (v3.6, Set59c093251, War 2 6:07:46) tugc v.i800 92 bie (Entel) on wings type "copyrights, "exedits” or "license Q™ for nore intornation, p> rine (ass), Firacaback (mort recent es11_ Last) File "", Line 1, in Prine (aes) manebrcor: nane ‘Print’ ‘9 not defined ‘or example, fAaueeraeing Logleat Error jx fost inpaeyEater a mister: fy = flonetinpuc(znter a misters 9 b= mys wve entered £8:1,2) print’ {the average of the two nurbers you ha eof the two numbers the user enters. But because The ab le should calculate the avera Ree enc ia uated before addition), the program will of the order of operations in arithmetic (division is eval not give the right answer; this is known as logical error /Users/preoti/appoata/Local/Programs/Python/ “| J evthona7-32/pr0y Logicerrori py As a result, you will get 5.0 as the output instead of 3.5. To rectify this problem, we will simply add parentheses: /sers/preets/Aopbata/Loeal/PFograns/Pyehon/ eyehond?-22/pr0g dogieersoct py What is Exception Handling Every programming language that we work with hhas some mechanism to handle an error that occurs during a program execution. Likewise, Python also provides a complete mechanism for handling an error when it occurs. This ‘mechanism is called Exception Handling Exception: Technically, an error is termed as Exception. An exception is an error that happens during the execution of a program. If an exception is not caught, the program is terminated, =o Fig. 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. Learning Tip: Exceptions are often used with network and file operations. When an exception is raised on account of some error, the program ‘must contain code to catch this exception and handle it properly. 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 gives information regarding the line number(s) along with the function calls that caused the exception. (i) Try bloc! it. If any code within the try statement causes an error, execution of the code will stop and jump to the except statement. Try block constitutes a set of codes that might have an exception thrown in. (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. ‘CM: 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. | 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. When an exception occurs in the program, we say that exception was raised or thrown. Next, we deal with it and say it is handled or caught. And the code written to handle it is known as 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). x aia” - “dial © raise Statement raise statement allows the program to force @ Python ‘ically raises an exception w! arts ised /thrown, I Jet it propagate further: specified exception to occur at run-time hhen it encounters an error during i t is up to caller function to 4 program execution. Once an exception is ra P either handle it using try/except statement or Use rae to force an exception: =D Fig, 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, You can also give your 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 provided. + traceback section succeeds the argument when any exception is raised or thrown. gar SEN SR once ce ‘or example, Lb pea.ecentoy Ciotonisooa.ecepiay G55) = Te Ges 52 Taisa Exception('x should not exceed 51) python 3.6.5. 2a, War 28-2018, 16:07 | eg yrype “copyright”, “credita* or “Meense()" for more infor sara FESIART: c+ /pytnon36/prog ‘oge racene oa, ase): honse/prog excep spy", e2eaptton Soak’ gl, 2, tn nodes mCePL.py Fig, Stb) ralsing/throwing an excepugy ‘We will now learn about some standarc We will now learn about some standard built-in exceptions available which F lable which are described in Compute So rie Table 1: Common Python Exceptions NameError Raised when an identifier is not found in the local or global namespace. TypeError Raised when an operation or function is attempted that is invalid for the specified data type. ValueError Raised when a builtin operation or function receives an argument that has the right type but an inappropriate value, ZeroDivisionError At Raised when division or modulo by zero takes place for all numeric types ibuteError 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. lOError Raised if the file requested cannot be opened, or failure of I/O operation. IndexError Raised when an index is not found in a sequence, i, 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 readlinest)), 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 you are trying to use a variable that doesn't, exist in the current environment. Itis raised when a function name or variable name is not found in the local or global namespace. If you 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. You cannot refer to them from outside the module/function where they are defined. For example, Le pro. mcendey -Clomonsspon messeny 06s) - > TE print (sun of two nusbers=", nuntenn3) Python 2.6.5, (va.6-5:f59c0ss2b4, war 28 2018, 16:07:46) 4 fuse v.1900 2 pit (Intel) } on vinse yes “copyright™, "eredite" of "iicense()” for more info [ESTART: ¢:/pytnon36/prog_excep2-PY Gs/pyenonse/prog_excep2-py", ine 5, in ‘Bin of tuo neabersé*, Hum1snums) ous is not detines 3. Gla): Namek ror exception ) ‘The given screenshot gives the description about NameLrror, which consists of— (Traceback, which describes a list ofthe functions which were running and displayed at the time of occurrence of the exception. path where in the program the exception has occurred, ie, (ii) The second line defines the given example along with the line name of the program, which is prog.excep2,py in the number: (ili) The third line shows the actual place of error, /e,, the statement in which the error has occurred which is print() method. {iv) The fourth and the last ine explains that the exception hr undefined variable num3. ‘Thus, from the above example, we can say that the exception NameBrror usually cont ‘as been raised because of the ributes asa result of + Undefined variable + Amistyped variable or function name + The name was to be enclosed within the quotes ‘TypeError: This type of error is raised when an operation or function is attempted that ig invalid for the specified data type. This type of exception may result from any of the following possible reasons © When you are trying to use a value improperly, For example: indexing a string, list or tuple 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. + You 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 you are invoking the method on an object with the right type and providing the other arguments correctly. Broamiriey Gpmovieamaeninia = 5 RE) pasha ae START! C*/python36/pe09_excepd.py = Pesnt (Sim of toe nabs ypetseor: mist be ats, noe ine Set PY", Tne 6, in age int (input (mnter your age + ")) Enter your age"! 018 Freaceback. (most zecant cat ast) File "epyshel2#0>", Dine 2, in age~ Int (input ("Enter your age * ")) auusczoet ieisa tera torre den nase 20: as" Fig. 6( /alueEtror 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. LB ros meet lamers meptny B65) = lpunrevan (input (Yanter a muaber”)) EsTART® cs /python36/p409_sxcePt. PY J[tracenack (most recent cal ast) [tiie sc:rpythonse/pscg_excent:py", Une 4, in modules eeropivintonzivert division by zero Si Fig. 6(4): ZeroDivisionError exception (c) AttributeError: This exception is raised when an object does not find an attribute, You are trying to access an attribute or method that does not exist. Check the spelling! You 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 you 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 you are using a method not associated with a particular object like list holding integer values and you are trying to use append() method which is not acceptable and, hence, AttributeError exception is thrown as shown in Fig, 6(e)). ia \s, Here are the differen You can use the try-except statement to gracefully handle exceptions. 1 a methods for handling exceptions in Python: Method 1: try and except block ‘The try and except block in Python is used to catch and handle exceptions. Python executes code following the try statement as a “normal” part of the program. The code that follows except statement is the program's response to any exceptions in the preceding try clause, Learning Tip: Python provides three keywords to deal with ‘exceptions: © raise ew + except Exception handling has two steps + Ralsing or Throwing + Catching Iyou have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code ina try: block When we use try.except block in the script and an error is encountered, a try block code execution is stopped and transferred down to the except block, unt code <2) Fig. 8: Using try and except block ‘Syntax: try: You do your operations here except: Ifthere is an exception, then execute this block. Example: With reference to Fig. 6(a), the program was numbers, with an error (NameError) in the print() statemé any exception handling mechanism, the program terminal This program can be modified and written using trysexc Provided to the user on the occurrence of any interrupt, written to calculate the sum of two lent. In the absence of try statement or ted abruptly and the execution halted et block so that a proper me: ge is Let us rewrite Fig, 6(a) example using try..except block, ro Roe EXPLAI If we ec prograr As ther executi the exc Let us t Examp! EXPLAN, In most This is ar This prog number In the san 0 as the impossib| In this ey exception not defin In the giv Ea EXPLANATION: If we compare the output of the example program in Fig, 6(a) and Fig. 9, we find that the latter program does not end abruptly but displays an error message. ‘As there is an error in the print statement (variable num3 is not declared), a try block code | execution is stopped and transferred down to the except block, The print statement present in the except block is executed. Let us take another example to explain try..except block, Example: To perform division of two numbers. | eee eee P aiviaing two ninbers *qumineval (input ("Eater aividond™)) unsenunt//nun2 % er as ocewered") # ccr/pytnon36/pz0g_excep)-py = Enter ivicend 30 ate: sivisoe4 | zerooision Exception asd sng ty_ecept ane guotlent ts = © Cs and splyng proper message othe ust Fig. 10: Exception handling using try..except EXPLANATION: In most cases, an exception causes a program to abruptly halt. For example, look at Fig. 10. shis is an example of gracefully avoiding an exception. ‘This program gets two numbers from the user and then divides the first number by the second number, In the sample running of the program, however, an exception occurred because the user entered 0 as the second number. (Division by 0 causes an exception because it is mathematically impossible.) In this example the program does not end abruptly when an error occurs. If we do not use exceptions in tl not defined. But here it simply throws error message and continues to execute further. program, it will terminate when we enter divisor as 0 because division by 0 is In the given code, the error message does not display the type of error: To know more about the errors, we can use multiple except statements. untered, a try Block code execution mea orisenct ‘CTM: When we use tyiexcept clause the script and an er a Is stopped and transferred down to the except block. Method 2: try..except with else block fee odie whi The else clause of try statement is used to specify the code executed in case no exception inten except s ye i In such ane = no exception. | As you saw earlier (in syntax errors topic), oon wil tiroe an esception| cra Ths ets ae fae eae crash the program if it is unhandled. The except block determines how your programy Fesponds to exceptions Example: Exception Computer Science with aa Hie gostiene so=¢ Division by tere not oetined Enter divisor, 5 ite qotient = 20 ig. 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 has occurred. ‘© Ifthat particular exception (which has occurred) is not specified in any except block, then the control is transferred to the except block without any exception name. ‘* Ifneither of the above two cases are met (there is no except clause handling that particular exception and there is no except clause without any exception name), then the script terminates abruptly as it happens when no try statement is used, (Coirene Benton Name (jicept ception Names) > “anti doe Sr Fig, 13: try with multiple except blocks oe) Col w tt Pat go ef sear ean | 3" (ys 4:0159¢0932b4, War 28 2018, 6°32 bee tineety | on vine frype “copyright”, areaite* or "Lieanse()* for more intormaton [RESTART: ci/python’é/ptog_excep9.py ~ |[eseianie “not present Guotlane 6S = 25 Soy Fig. 16: try..except with finally clause EXPLANATIO) In this program the print statement given in the finally clause j always executed irrespective of whether exception occurs or not. So donelli! gets displayed after every iteration of while loop. Rosie BYTES > raise aos ou to trow an exception manly > Runtine rors oc dring the executon of» protam > Exceptions may ocr even ifthe program is tee toma > inthe wy clase, al statements ar exeeted ont tn © called Exceptions, tyPes of errors, tion is encountered, > except is used to catch and handle the exception(s) that a re encountered In the ty claus, > else lets you code sections that should run only when no - exceptions are enco tio untered in the try clause. > finallyenables you to execute sections of code that shoulda, exceptions meyer, with orwithoutany Previously encountered ey aoe An An OBJECTIVE TYPE QUESTIONS ee 1. fill in the blanks. {a} On encountering a a are removed by the useg. 7 the Interpreter does not execute the program unless these errors 4 (b) When a number is divided by 0, error J @ is a Python object that represents an erro ees: sed when a local or global variable is not defined. block holds the code to be run and checked for any erro, if exist. ‘ans. (a). Syntax nee ny (©) ZeroDivisionérror _(e) Exception (d) Nametrror 2, State whether the following statements are True or False {@) Valuetrror occurs due to wrong indentation in a program. (6) Exception and error are the same objects (€) Exceptions are caught using try block (d) The order of exception handling in Python is try, followed by except, and then finaly (e) Catch is a part of exception handling fans. (a) False (b) False (c) True (4) True _(e) False 3. Multiple Choice Questions (MCQs) @ 1 SE Hehe SCE a en iT eS {i) Compile time error (ii) Logical error (ii) Runtime error (iv) Exception (b) An interrupt or forced disruption that occurs when a program is run or executed is termed as (i) Compile time error (i) Exception (ii) Buntime error (Iv). Logical error {c) Which of the following keywords are not specific to exception handling? (i) try (il) except (ii) else (i) finally (4) Which block is a mandatory block in exception handling process? () try (il) except (i) finally (iv) else {e) Forced exceptions are indicated using which of the following Keywords? () try (i) except i) finally (w) alse Ree | HH (oc Ge) AC) Ce ae EeEnQUESTIONS ——=————— so an, | aehae EDefinean Exception? so. some contradictory or unusual stuntion which can be encountered re bieck ond sing ans in the except-block, The excep Bock indleates ‘the action to Boies Dlock and put pea: Sed within the corresponding try block. Ifo exception is raised, ree ante of excetion raeed wir Nee escemaly and the except lock sHePed Bi tony cise clauses can be added into a trVe#rePh block? ‘Ans, Only one. 4. Why finally clause is cal Ans. & finally clause is alway: ‘or not. When an exception M (or it has occurred in an exce' er program. n other words, an exception an error that happens during led as cleanup? afr a ont ee aed) ance se es eer erat afr he nly anon be ne How many except clauses can be included in a try block? ‘Any number of except clauses. What happens when an abnormal condition happens in a program? ‘When an abnormal condition to the program flow has been detected, an Instance of an exception object Is created. Its then “thrown” or “raised” to code that will catch i. . What type of error it will produce when you type: Result = “Python” + 10 Name the error and error message, . The error is: Typetrror The error message is: Can't convert ‘Int’ object to str implicitly 3. What type of error it will produce when you type: while True print("Hello world") The error is: SyntaxError: invalid syntax ‘What type of error it will produce when you type: ‘48 5. The error is: TypeError ). What will be the output of the following program? X,Y, a= 5,0,None print ("al try print ("b") a=x/y print ("co") except: print ("d") print ("e") print (a) The output is None . What output the Python code shall produce? Justify your answer, print (*C') except ZexoDivisionError except pint ('D') The code will produce the following output Explanation: The statement print ‘A’ wil produce A. ‘The fist statement of the try block is print ‘8’ and will produce B. ‘Thenextiine intry block's a=x/y which generates a ZeroDivisionérror because, x=6 and y=0, /e, expression. has pero as the denominator. So, the try block wl follow the except. ZeroDivisionError: with statement print‘ and will produce F. Cente ia nice) The fll «i, (ai (i) Bot (i) Bo (i) i (wv) Ai ern 42, What will be the output o Pe Put of the following p Beé print (‘One') try: print ("Two") X=8/A print ("Three") except ZeroDivisionzrror: print (B¥2) : print (‘Four’) vthon code Code? Explain the try and except used in the code. except: print (b*3) print ('Five') ‘ans. The output is: one Tuo 12 Four Inthe given code, all the statements within the try-block will be executed smoothly til ZeroDivisiont for ‘occurs. fa division expression has zero as the denominator, this causes a ZeroDivisionError to be raised nd 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 zero while dividing X by Y and displays the quotient otherwise Bretyronetion to demonstrate try. ..except.. else Dlock x= int (input ("Enter first number: ")) y= int (input ("Enter second number: ")) 1 &r¥) print ("Two nos az try: result = x/¥ except ZeroDivisionError print ("cannot divide Py 7ex0 ) ‘of exception is raised within the here ing try block, When alvin ex@resion Bs SE the , result) QuesTIONS = D EASONING BASE! ae two statements Assertion and reasoning. Each question has four choices (, Thefotowing uestions corr re ight ofthese statements, choose the most ‘appropriate option. i), (ii), (iv) — onl ‘one of which is corr i (i) Both A and R are true and B ransom ofA Fey eta are true but Fis not te ru (iil) is true but R is false: iv) Ais false but R is rue: 1, Assertion (A): Exception han’ Reasoning (R): Exception Nam a program 2. assertion (A): Except Reasoning (RY: Program rosie © ‘exceptions jon of A. es of errors and exceptions T handling anomalous situations a during the execution of ling han ie sponsible fo gis re: -ywords to handle rom normal code ie yde uses specific ke! is separate f de is set exception handling CO jon handling © : vifferent while excel 3. Assertion (A): Exception handling code is clear and block based in Python. Reasoning (R) The code where unexpected runtime exception may occurs separate from the code where the action takes place when an exception occurs ‘Gls 4. Assertion (A): No matter what exception occurs, you can always make sure that some common action takes place forall types of exceptions. Reasoning (Rh: The finaly block contains the code that must execute ane 2A) 8 UNSOLVED QUESTIONS 1, What all can be the possible outputs of the following code? def myfunc(x=None) : result =" if x ds None: "No argument given’ result = "Zero" elif 0 print (445) Most syntactical errors occur at the time of program execution and the interpreter points them out for you. Fixing the error is made easy because the interpreter generally tells you what to fix with considerable accuracy, TM: Syntax errors are errors that occur due to Incorrect format of a Python statement. They occur while | the statement is being translated to machine language and before being executed, J ‘A few more examples of syntax errors are shown below in Fig. 2. Type "copyright*, “credits” or "license ()" for more 4 nfornation. pgoraaes fstatement. Syntaxtrror: invalid syntax D> 10 Kons, Syntaxszror: invalid syntax Seema statement [Syntaxerror: vissing parentheses in catl to ‘print’. bid you mean print ("hello")? >> Ist (47576) [Syntaxéeror: invalid syntax. osm tor 4 in range (20) Beane fstarement SyntaxBrror: expected an indented block ‘statement statement 4 Fig. 2: Other types of Syntax Errors Let us understand the reason behind the occurrence of each error given in the above example, 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, 3. Statement 3 generates syntax error because of missing parentheses () with print() method 4. Statement 4 generates syntax error because of use of semicolon inst ‘ead of comma ina list declaration, 5. Statement 5 generates syntax error because of improper indentation. Run-time Error Arun-time error occurs after Python interpreter inter prets the code you write a begins to execute it, Run-time errors come in different types and some are h: You know you have a run-time error when the application sudde an error (exception) dialog box or when the user complains results in abnormal progrs nd the computer ard to find, nly stops running and displays about erroneous output Ie eval "am termination during executi ape eet ema In the above example, we have typed the Print() statement instead of print(), which is syntactically So ae eines Lot Al inc Log but Soni You For 10+ to fi For example, Fe at Sek 1g ope Wow HOR SES Eee Python 3.6.5 (v3.6.5:£59c0932b4, Mar 26 2018, 16: ” 07:46) [Se v.1900 32 bit (Intel)] on wins? ‘Type "copyright", "credits" or "License()" for mo ze information. >>> 103 (1/0) Traceback (most recent call last) File "", line 1, in ; 10 (1/0) zeroDivisiongrror: division by zero Fig. 3: Example of Run-time Error The above statement is syntactically correct but won't yield any output. Instead, it shall generate an error 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 Performing an operation on incompatible types : Using an identifier variable which has not been defined Accessing a list element, dictionary value or object attribute which doesn't exist ati vee Trying to access a file that doesn't exist | ‘CIM: Errors are exceptional, unusual and unexpected situations and they are never part of the normal flow of a program. In Python, such unusual situations are termed as Exceptions, Exceptions are usually run-time errors. Logical Errors A logical error/bug (called semantic error) does not stop execution but the program behaves incorrectly and produces undesired/wrong output. Since the program interprets successfully ‘even 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 without crashing but produces an incorrect result, The error is caused by a mistake in the program's logic. You is ‘won't get an error message because no syntax or run-time error has occurred. Some examples of logical errors are: ‘+ Using the wrong variable name for calculations, + Using integer division or modulus operatoi place of division operator + Giving wrong operator precedence, You will have to find the problem on your own by reviewing all the relevant parts of the code. For example, if we wish to find the average of two numbers, 10 and 12, and we write the code as 10 + 12/2, it will run successfully and produce the result 16, which is wrong. The correct code to find the average should have been (10 + 12)/2 to get the output as 11. aan i 7018, 1607846) 0" tor more snto restart: ct/python36/prog_excepS-PY @ peer eden eet 5 /eythonserocog axceps-py", Line 2, Stsgeeppens (0) ae Fig. 6(e}: AttributeE or exception Jement of a dictionary (©) KeyError: This type of error occurs when you are trying to access an el , using a key that the dictionary does not contain: [eyenen acct ted. ¢.512S5c050054, war ZO 2OK8, 1erOTHa S8o"32 nie tneeiy} ca neat egethek RE cet out taro Sree ial? ae HA An hal Fig. 6(f): KeyEtror exception aa H82 (B) IndexError: The index you are using to access a list, string, or tuple is greater than its We {eogth minus one, This exception is raised when an index is not found in'a sequence, In ee ' otter words, it oceurs whenever we try to access an index that is out ofa valia range. x Err BG, EH, Te Pye ceoyriots, “ereitanor *Heansed)* for nore sator Poe colors « crea, tgren', mpiver : 53 Shorea) ‘ Pescaback fost recent cat) ast): Tile Stents aie 1, ty nates si seaertrror! Lise Sndex out of range \dexEtror exception () 10Error: This exception occurs whenever there is an erro) ; trying to delete a file j i On. In all these situations, Tor exception is raised r related to input/output such as Ws removing USD ehile re where some ; output operation, 10Er ee cae Sar fe ta Rte wre yenon 2.6.8" v3.6.5its9cooa204, Mar 20 2018, 16107146) (HE ¥-1900 92 Bit (Gate e0 winks oe "Licansa|)* for nore Antoemation. Fig, 6(h): |OError exception (i) 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 | or in looping statements (compound statements) or even in defining user-defined functions/ modules, on wina2 edits” or *License()" for nore information. for Aum Ja rango(2imkt) + BM num) Syataxtrror: expected an indented block Fig. 6{i): Indentation exception 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. We have noticed that whenever an exception occurs, a Traceback (already explained in the previous topics) object is displayed which includes error name, its description and the point of ‘occurrence of the error such as line number. Error handling in Python involves the following steps: + Firstly, the moment an error occurs the state of execution of the program is saved. + Normal flow of the program is interrupted (stopped for a moment). * A special function or piece of code known as exception handler is executed. + Execution of the program is resumed with the previously saved data. process of error handling i called exception handling, Fig. 7: Exception Handling in Python. Method 4: Syntax: a ‘The finall try: circumstan You do your operations here occurred in oe In order to except Exception (Name) ~ I: If there is exception-I, then execute this block. except Exception (Name) - Il: If there is exception-tI, then execute this block. ‘except Exception (Name) ~ II If there is exception III, then execute this block. you to do si except: If there is no exceptions with the specified name given above, then execute this block, eee ee eS ea] executed only if there is no exception, oe x ' i |orcwpt Bareotvistenserors prine (“oti ra ‘oy taro nt enttsaa} “eredite” or *1icens¢1)~ for nore intornatica. re Fig, 14: try with multiple except Blocks —4 7 soto not defined’ occa When ther ener''asthe dang ff salosee fa terror "Variable not present” occurs. nan except clause ception Handi Lenny Method 4: try...except with finally block ‘The finally block is is called cleans circumstances, ie., a “finally” ran ape ermlnston a seloeeg ; a ockdieral laus se it is executed under a gccurred in a try block always executed i under all renee irrespective of whether an ex ‘an exception has inorder to implement some en some sort of action to cl a etc Tag We finaly cae lean up after executing your code, Python enables Fig. 15: Using try except with inaly Block Syntax: try: You do your operations here except Exception-I: this block. exception-I, then execute If there is except Exception-Il: if there is exception, then execute this block. els «then execute this block. if there is no exception finally: Always ©? xecuteds jock is always executed NO matter what.

You might also like