How to Create Exception to Input Value Again

29. Errors and Exception Handling

Past Bernd Klein. Terminal modified: 27 Feb 2022.

Exception Handling

An exception is an error that happens during the execution of a program. Exceptions are known to non-programmers as instances that exercise not conform to a general rule. The name "exception" in informatics has this meaning too: It implies that the trouble (the exception) doesn't occur frequently, i.e. the exception is the "exception to the dominion". Exception handling is a construct in some programming languages to handle or bargain with errors automatically. Many programming languages like C++, Objective-C, PHP, Java, Blood-red, Python, and many others have built-in support for exception handling.

Error handling is generally resolved by saving the state of execution at the moment the mistake occurred and interrupting the normal period of the program to execute a special function or piece of code, which is known every bit the exception handler. Depending on the kind of error ("division past zero", "file open fault" and so on) which had occurred, the error handler tin "gear up" the problem and the programm can be connected afterwards with the previously saved information.

Python logo with band aid

Exception Handling in Python

Exception handling in Python is very similar to Java. The lawmaking, which harbours the gamble of an exception, is embedded in a try block. While in Java exceptions are defenseless by catch clauses, in Python nosotros have statements introduced past an "except" keyword. It's possible to create "custom-fabricated" exceptions: With the raise statement it'south possible to force a specified exception to occur.

Allow's wait at a simple example. Assuming we want to ask the user to enter an integer number. If we use a input(), the input will be a cord, which we have to bandage into an integer. If the input isn't a valid integer, we will generate (enhance) a ValueError. We show this in the following interactive session:

            north            =            int            (            input            (            "Please enter a number: "            ))          

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

            while            True            :            attempt            :            n            =            input            (            "Please enter an integer: "            )            due north            =            int            (            north            )            suspension            except            ValueError            :            print            (            "No valid integer! Delight try again ..."            )            print            (            "Great, you lot successfully entered an integer!"            )          

It's a loop, which breaks only if a valid integer has been given. The while loop is entered. The lawmaking within the try clause will be executed statement by argument. If no exception occurs during the execution, the execution will achieve the break argument and the while loop will be left. If an exception occurs, i.east. in the casting of n, the rest of the try block will be skipped and the except clause will be executed. The raised fault, in our case a ValueError, has to match one of the names afterward except. In our example just one, i.e. "ValueError:". After having printed the text of the print statement, the execution does another loop. It starts with a new input().

We could plow the code above into a function, which can be used to have a foolproof input.

            def            int_input            (            prompt            ):            while            Truthful            :            endeavour            :            historic period            =            int            (            input            (            prompt            ))            return            age            except            ValueError            as            due east            :            print            (            "Non a proper integer! Try it again"            )          

We use this with our dog age example from the affiliate Conditional Statements.

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

OUTPUT:

Not a proper integer! Attempt it once more Not a proper integer! Try it once again Age of the domestic dog:  37            

Multiple Except Clauses

A try statement may have more than ane except clause for dissimilar exceptions. Simply at most 1 except clause will be executed.

Our side by side example shows a try clause, in which we open a file for reading, read a line from this file and catechumen this line into an integer. In that location are at least two possible exceptions:

          an IOError ValueError                  

Just in case we accept an boosted unnamed except clause for an unexpected error:

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

OUTPUT:

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

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

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

And if the file integers.txt is not readable, due east.m. if we don't have the permission to read it, we get the following message:

I/O error(thirteen): Permission denied

An except clause may name more than one exception in a tuple of error names, as nosotros see in the following example:

              endeavour              :              f              =              open              (              'integers.txt'              )              south              =              f              .              readline              ()              i              =              int              (              s              .              strip              ())              except              (              IOError              ,              ValueError              ):              print              (              "An I/O error or a ValueError occurred"              )              except              :              print              (              "An unexpected fault occurred"              )              heighten            

OUTPUT:

An I/O fault or a ValueError occurred            

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

              def              f              ():              x              =              int              (              "four"              )              try              :              f              ()              except              ValueError              as              e              :              print              (              "got information technology :-) "              ,              e              )              impress              (              "Permit's become on"              )            

OUTPUT:

got information technology :-)  invalid literal for int() with base of operations 10: 'iv' Let'southward get on            

the function catches the exception.

We will extend our example now then that the function will catch the exception directly:

              def              f              ():              try              :              x              =              int              (              "iv"              )              except              ValueError              as              e              :              print              (              "got it in the function :-) "              ,              e              )              endeavor              :              f              ()              except              ValueError              every bit              e              :              print              (              "got information technology :-) "              ,              eastward              )              print              (              "Let'south get on"              )            

OUTPUT:

got information technology in the function :-)  invalid literal for int() with base of operations 10: 'four' Let's get on            

As we have expected, the exception is caught inside the function and non in the callers exception:

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

              def              f              ():              try              :              x              =              int              (              "four"              )              except              ValueError              as              e              :              impress              (              "got information technology in the office :-) "              ,              due east              )              enhance              try              :              f              ()              except              ValueError              as              eastward              :              impress              (              "got it :-) "              ,              e              )              print              (              "Let's become on"              )            

OUTPUT:

got information technology in the function :-)  invalid literal for int() with base of operations ten: 'four' got it :-)  invalid literal for int() with base ten: 'iv' Let'southward get on            

Live Python training

instructor-led training course

Upcoming online Courses

Intensive Advanced Grade

28 Mar 2022 to 01 April 2022
30 May 2022 to 03 Jun 2022
29 Aug 2022 to 02 Sep 2022
17 Oct 2022 to 21 Oct 2022

Enrol here

Custom-fabricated Exceptions

Information technology's possible to create Exceptions yourself:

              raise              SyntaxError              (              "Distressing, my fault!"              )            

OUTPUT:

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

The best or the Pythonic way to do this, consists in defining an exception class which inherits from the Exception class. You lot will have to go through the affiliate on Object Oriented Programming to fully understand the post-obit case:

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

OUTPUT:

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

Make clean-up Deportment (try ... finally)

So far the try statement had always been paired with except clauses. But there is another way to use it likewise. The endeavor argument can be followed by a finally clause. Finally clauses are chosen clean-upward or termination clauses, because they must be executed under all circumstances, i.e. a "finally" clause is always executed regardless if an exception occurred in a try block or not. A simple example to demonstrate the finally clause:

              try              :              x              =              float              (              input              (              "Your number: "              ))              inverse              =              i.0              /              x              finally              :              print              (              "There may or may not accept been an exception."              )              print              (              "The changed: "              ,              inverse              )            

OUTPUT:

Your number: 34 There may or may non accept been an exception. The inverse:  0.029411764705882353            

Combining try, except and finally

"finally" and "except" tin can exist used together for the same effort block, equally it tin can be seen in the following Python example:

              endeavor              :              10              =              float              (              input              (              "Your number: "              ))              inverse              =              i.0              /              x              except              ValueError              :              print              (              "You should have given either an int or a float"              )              except              ZeroDivisionError              :              impress              (              "Infinity"              )              finally              :              print              (              "In that location may or may not accept been an exception."              )            

OUTPUT:

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

else Clause

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

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

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

OUTPUT:

This example receives the file proper name via a control line argument. So make sure that yous call information technology properly: Allow's assume that you lot saved this program as "exception_test.py". In this instance, yous have to phone call it with

          python exception_test.py integers.txt        

If y'all don't want this behaviour, only alter the line "file_name = sys.argv[one]" to "file_name = 'integers.txt'".

The previous example is nearly the same equally:

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

OUTPUT:

The main difference is that in the first example, all statements of the attempt block tin pb to the aforementioned error message "cannot open up ...", which is wrong, if fh.close() or fh.readlines() raise an error.

Live Python training

instructor-led training course

Upcoming online Courses

Intensive Avant-garde Grade

28 Mar 2022 to 01 Apr 2022
thirty May 2022 to 03 Jun 2022
29 Aug 2022 to 02 Sep 2022
17 October 2022 to 21 Oct 2022

Enrol here

rogersmect1964.blogspot.com

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

0 Response to "How to Create Exception to Input Value Again"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel