Oops Try Again Your Function Caused the Following Error List Index Out of Range

35. Errors and Exception Handling

By Bernd Klein. Last modified: xix Apr 2022.

Exception Handling

An exception is an error that happens during the execution of a program. Exceptions are known to non-programmers every bit instances that practice non adjust to a general rule. The proper noun "exception" in informatics has this significant too: It implies that the problem (the exception) doesn't occur frequently, i.e. the exception is the "exception to the rule". Exception handling is a construct in some programming languages to handle or deal with errors automatically. Many programming languages like C++, Objective-C, PHP, Java, Ruby, Python, and many others take congenital-in support for exception handling.

Fault handling is generally resolved past saving the state of execution at the moment the error occurred and interrupting the normal menses of the program to execute a special role or piece of code, which is known as the exception handler. Depending on the kind of error ("division by nil", "file open error" and and then on) which had occurred, the mistake handler tin "set" the problem and the programm can exist continued afterwards with the previously saved data.

Python logo with band aid

Exception Handling in Python

Exception handling in Python is very similar to Java. The lawmaking, which harbours the risk of an exception, is embedded in a endeavour block. While in Coffee exceptions are caught past catch clauses, in Python we have statements introduced past an "except" keyword. It'southward possible to create "custom-made" exceptions: With the heighten statement information technology'due south possible to force a specified exception to occur.

Let's await at a simple example. Assuming we desire to ask the user to enter an integer number. If nosotros utilize a input(), the input will be a cord, which we have to cast into an integer. If the input isn't a valid integer, nosotros will generate (raise) a ValueError. We testify this in the following interactive session:

            n            =            int            (            input            (            "Delight enter a number: "            ))          

With the aid of exception handling, we can write robust code for reading an integer from input:

            while            True            :            try            :            n            =            input            (            "Delight enter an integer: "            )            northward            =            int            (            n            )            pause            except            ValueError            :            impress            (            "No valid integer! Please endeavour once again ..."            )            print            (            "Smashing, you lot successfully entered an integer!"            )          

It'south a loop, which breaks merely if a valid integer has been given. The while loop is entered. The code within the try clause will be executed statement by argument. If no exception occurs during the execution, the execution volition reach the break statement and the while loop will exist left. If an exception occurs, i.due east. in the casting of n, the rest of the try block will be skipped and the except clause will exist executed. The raised error, in our case a ValueError, has to match one of the names later on except. In our case only one, i.east. "ValueError:". After having printed the text of the impress statement, the execution does another loop. It starts with a new input().

We could turn the lawmaking higher up into a function, which can be used to have a foolproof input.

            def            int_input            (            prompt            ):            while            True            :            effort            :            age            =            int            (            input            (            prompt            ))            return            age            except            ValueError            as            e            :            print            (            "Non a proper integer! Try it once again"            )          

We apply this with our dog historic period instance from the chapter Conditional Statements.

            def            dog2human_age            (            dog_age            ):            human_age            =            -            1            if            dog_age            <            0            :            human_age            =            -            ane            elif            dog_age            ==            0            :            human_age            =            0            elif            dog_age            ==            ane            :            human_age            =            14            elif            dog_age            ==            two            :            human_age            =            22            else            :            human_age            =            22            +            (            dog_age            -            2            )            *            v            render            human_age          
              age              =              int_input              (              "Age of your domestic dog? "              )              print              (              "Age of the domestic dog: "              ,              dog2human_age              (              age              ))            

OUTPUT:

Not a proper integer! Attempt it once again Not a proper integer! Endeavour it again Age of the dog:  37            

Multiple Except Clauses

A try statement may take more than one except clause for different exceptions. But at most i except clause will exist executed.

Our next example shows a try clause, in which nosotros open a file for reading, read a line from this file and convert this line into an integer. There are at to the lowest degree two possible exceptions:

          an IOError ValueError                  

Just in case we have an additional unnamed except clause for an unexpected fault:

              import              sys              endeavor              :              f              =              open              (              'integers.txt'              )              s              =              f              .              readline              ()              i              =              int              (              southward              .              strip              ())              except              IOError              every bit              e              :              errno              ,              strerror              =              e              .              args              print              (              "I/O mistake(              {0}              ):                            {i}              "              .              format              (              errno              ,              strerror              ))              # east can be printed directly without using .args:              # print(e)              except              ValueError              :              impress              (              "No valid integer in line."              )              except              :              print              (              "Unexpected error:"              ,              sys              .              exc_info              ()[              0              ])              heighten            

OUTPUT:

I/O error(2): No such file or directory            

The handling of the IOError in the previous example is of special interest. The except clause for the IOError specifies a variable "due east" later the exception proper noun (IOError). The variable "e" is bound to an exception instance with the arguments stored in instance.args. If we call the higher up script with a non-existing file, we get the message:

I/O error(two): No such file or directory

And if the file integers.txt is non readable, eastward.grand. if we don't have the permission to read it, we get the following message:

I/O error(13): Permission denied

An except clause may name more than than i exception in a tuple of fault names, as we encounter in the following example:

              attempt              :              f              =              open up              (              'integers.txt'              )              s              =              f              .              readline              ()              i              =              int              (              s              .              strip              ())              except              (              IOError              ,              ValueError              ):              print              (              "An I/O mistake or a ValueError occurred"              )              except              :              print              (              "An unexpected error occurred"              )              enhance            

OUTPUT:

An I/O error or a ValueError occurred            

We want to demonstrate now, what happens, if we call a function within a try cake and if an exception occurs inside the function call:

              def              f              ():              x              =              int              (              "4"              )              try              :              f              ()              except              ValueError              as              e              :              print              (              "got it :-) "              ,              e              )              impress              (              "Let's get on"              )            

OUTPUT:

got it :-)  invalid literal for int() with base ten: 'iv' Permit'south get on            

the function catches the exception.

We will extend our example now and so that the function will catch the exception straight:

              def              f              ():              try              :              ten              =              int              (              "4"              )              except              ValueError              equally              e              :              impress              (              "got it in the function :-) "              ,              e              )              endeavour              :              f              ()              except              ValueError              as              e              :              print              (              "got it :-) "              ,              east              )              print              (              "Permit'south get on"              )            

OUTPUT:

got it in the part :-)  invalid literal for int() with base ten: 'four' Let's get on            

Equally we have expected, the exception is caught inside the office and not in the callers exception:

We add now a "raise", which generates the ValueError again, so that the exception will be propagated to the caller:

              def              f              ():              endeavor              :              x              =              int              (              "four"              )              except              ValueError              as              east              :              impress              (              "got it in the role :-) "              ,              e              )              raise              endeavor              :              f              ()              except              ValueError              as              east              :              print              (              "got it :-) "              ,              e              )              print              (              "Permit'south get on"              )            

OUTPUT:

got it in the part :-)  invalid literal for int() with base 10: 'four' got it :-)  invalid literal for int() with base 10: '4' Let'southward become on            

Live Python training

instructor-led training course

Upcoming online Courses

Enrol hither

Custom-fabricated Exceptions

Information technology's possible to create Exceptions yourself:

              raise              SyntaxError              (              "Sorry, my fault!"              )            

OUTPUT:

Traceback              (about recent call last):   File              "C:\\Users\\melis\\Anaconda3\\lib\\site-packages\\IPython\\cadre\\interactiveshell.py", line              3326, in              run_code              exec(code_obj, self.user_global_ns, cocky.user_ns)                              File                            "<ipython-input-15-a5649918d59e>"              , line                            1              , in                            <module>                              raise SyntaxError("Distressing, my fault!")                              File                            "<string>"              , line                            unknown              SyntaxError              :              Sorry, my error!            

The best or the Pythonic way to practise this, consists in defining an exception class which inherits from the Exception class. You volition have to go through the chapter on Object Oriented Programming to fully sympathize the following example:

              grade              MyException              (              Exception              ):              laissez passer              raise              MyException              (              "An exception doesn't always prove the rule!"              )            

OUTPUT:

              ---------------------------------------------------------------------------              MyException              Traceback (near contempo call last)              <ipython-input-3-d75bff75fe3a>              in              <module>                              2              laissez passer                              3              ----> 4                                          raise              MyException(              "An exception doesn't e'er prove the rule!"              )              MyException: An exception doesn't always prove the rule!

Clean-up Actions (try ... finally)

So far the effort argument had always been paired with except clauses. Merely at that place is another way to use it likewise. The try statement can be followed past a finally clause. Finally clauses are chosen clean-upward or termination clauses, considering they must be executed under all circumstances, i.e. a "finally" clause is ever executed regardless if an exception occurred in a endeavour cake or non. A simple instance to demonstrate the finally clause:

              try              :              x              =              float              (              input              (              "Your number: "              ))              inverse              =              1.0              /              x              finally              :              print              (              "There may or may non take been an exception."              )              print              (              "The changed: "              ,              changed              )            

OUTPUT:

Your number: 34 There may or may not take been an exception. The changed:  0.029411764705882353            

Combining attempt, except and finally

"finally" and "except" can be used together for the same try cake, equally it can be seen in the following Python case:

              try              :              x              =              float              (              input              (              "Your number: "              ))              changed              =              1.0              /              x              except              ValueError              :              print              (              "You should take given either an int or a bladder"              )              except              ZeroDivisionError              :              print              (              "Infinity"              )              finally              :              print              (              "There may or may not have been an exception."              )            

OUTPUT:

Your number: 23 There may or may non have been an exception.            

else Clause

The try ... except statement has an optional else clause. An else block has to be positioned later all the except clauses. An else clause will be executed if the attempt clause doesn't raise an exception.

The following instance opens a file and reads in all the lines into a listing called "text":

              import              sys              file_name              =              sys              .              argv              [              1              ]              text              =              []              try              :              fh              =              open up              (              file_name              ,              'r'              )              text              =              fh              .              readlines              ()              fh              .              shut              ()              except              IOError              :              impress              (              'cannot open'              ,              file_name              )              if              text              :              impress              (              text              [              100              ])            

OUTPUT:

This example receives the file name via a command line argument. Then make sure that you call information technology properly: Let'south presume that you saved this program as "exception_test.py". In this case, you take to call it with

          python exception_test.py integers.txt        

If you lot don't want this behaviour, simply change the line "file_name = sys.argv[1]" to "file_name = 'integers.txt'".

The previous example is nearly the same as:

              import              sys              file_name              =              sys              .              argv              [              1              ]              text              =              []              endeavour              :              fh              =              open              (              file_name              ,              'r'              )              except              IOError              :              print              (              'cannot open'              ,              file_name              )              else              :              text              =              fh              .              readlines              ()              fh              .              close              ()              if              text              :              print              (              text              [              100              ])            

OUTPUT:

The main difference is that in the kickoff case, all statements of the effort block can lead to the aforementioned error message "cannot open up ...", which is wrong, if fh.close() or fh.readlines() enhance an error.

Live Python training

instructor-led training course

Upcoming online Courses

Enrol here

burnshuserapposse.blogspot.com

Source: https://python-course.eu/python-tutorial/errors-and-exception-handling.php

0 Response to "Oops Try Again Your Function Caused the Following Error List Index Out of Range"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel