Why Does Error Occur When I Read an Int Value From File in While Loop Java

29. Errors and Exception Handling

By Bernd Klein. Last modified: 27 Feb 2022.

Exception Handling

An exception is an error that happens during the execution of a programme. Exceptions are known to not-programmers as instances that practice not suit to a full general rule. The name "exception" in computer science has this meaning as well: Information technology implies that the trouble (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 accept built-in support for exception treatment.

Error handling is by and large resolved by saving the state of execution at the moment the error occurred and interrupting the normal flow of the program to execute a special function or piece of code, which is known as the exception handler. Depending on the kind of error ("partition past zero", "file open up error" and then on) which had occurred, the fault handler can "ready" the problem and the programm tin be continued afterwards with the previously saved data.

Python logo with band aid

Exception Handling in Python

Exception handling in Python is very similar to Coffee. The lawmaking, which harbours the take a chance of an exception, is embedded in a try block. While in Coffee exceptions are caught past catch clauses, in Python we take statements introduced by an "except" keyword. Information technology'south possible to create "custom-made" exceptions: With the raise statement it'south possible to strength a specified exception to occur.

Let's wait at a simple example. Assuming we desire to ask the user to enter an integer number. If nosotros use a input(), the input volition be a string, which we have to cast into an integer. If the input isn't a valid integer, we will generate (heighten) a ValueError. We show this in the post-obit interactive session:

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

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

            while            True            :            attempt            :            n            =            input            (            "Please enter an integer: "            )            due north            =            int            (            n            )            break            except            ValueError            :            print            (            "No valid integer! Delight try once more ..."            )            print            (            "Smashing, y'all successfully entered an integer!"            )          

It'south a loop, which breaks but if a valid integer has been given. The while loop is entered. The code inside the effort clause will be executed argument by argument. If no exception occurs during the execution, the execution will achieve the break statement and the while loop will be left. If an exception occurs, i.e. in the casting of due north, the rest of the try block volition exist skipped and the except clause will exist executed. The raised error, in our case a ValueError, has to match one of the names after except. In our example only ane, i.due east. "ValueError:". Later having printed the text of the print statement, the execution does another loop. It starts with a new input().

We could turn the code above into a part, which tin can be used to have a foolproof input.

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

Nosotros use this with our dog age instance from the chapter Conditional Statements.

            def            dog2human_age            (            dog_age            ):            human_age            =            -            one            if            dog_age            <            0            :            human_age            =            -            1            elif            dog_age            ==            0            :            human_age            =            0            elif            dog_age            ==            ane            :            human_age            =            xiv            elif            dog_age            ==            2            :            human_age            =            22            else            :            human_age            =            22            +            (            dog_age            -            2            )            *            5            render            human_age          
              age              =              int_input              (              "Age of your canis familiaris? "              )              print              (              "Age of the dog: "              ,              dog2human_age              (              historic period              ))            

OUTPUT:

Not a proper integer! Try it again Non a proper integer! Try information technology again Historic period of the dog:  37            

Multiple Except Clauses

A try argument may take more than than 1 except clause for different exceptions. But at nigh one except clause volition be executed.

Our next example shows a effort clause, in which we open a file for reading, read a line from this file and convert this line into an integer. There are at least two possible exceptions:

          an IOError ValueError                  

Just in example we take an additional unnamed except clause for an unexpected fault:

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

OUTPUT:

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

The handling of the IOError in the previous case is of special interest. The except clause for the IOError specifies a variable "e" after the exception name (IOError). The variable "e" is spring to an exception case with the arguments stored in example.args. If we phone call the above script with a non-existing file, we get the bulletin:

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

And if the file integers.txt is not readable, due east.k. if we don't take the permission to read it, nosotros go the post-obit message:

I/O error(13): Permission denied

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

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

OUTPUT:

An I/O error or a ValueError occurred            

Nosotros want to demonstrate now, what happens, if we telephone call a part within a endeavour block and if an exception occurs inside the function call:

              def              f              ():              x              =              int              (              "four"              )              endeavour              :              f              ()              except              ValueError              as              e              :              print              (              "got it :-) "              ,              e              )              impress              (              "Let'southward become on"              )            

OUTPUT:

got it :-)  invalid literal for int() with base of operations ten: '4' Let's get on            

the function catches the exception.

Nosotros volition extend our example now so that the function volition catch the exception directly:

              def              f              ():              try              :              x              =              int              (              "four"              )              except              ValueError              as              east              :              print              (              "got it in the role :-) "              ,              e              )              attempt              :              f              ()              except              ValueError              every bit              e              :              print              (              "got it :-) "              ,              east              )              print              (              "Permit's go on"              )            

OUTPUT:

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

As we have expected, the exception is defenseless inside the function and not in the callers exception:

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

              def              f              ():              attempt              :              x              =              int              (              "four"              )              except              ValueError              as              e              :              print              (              "got it in the office :-) "              ,              due east              )              heighten              try              :              f              ()              except              ValueError              as              e              :              impress              (              "got it :-) "              ,              e              )              print              (              "Permit's go on"              )            

OUTPUT:

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

Alive Python preparation

instructor-led training course

Upcoming online Courses

Intensive Advanced Form

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

Enrol here

Custom-made Exceptions

It's possible to create Exceptions yourself:

              raise              SyntaxError              (              "Deplorable, my mistake!"              )            

OUTPUT:

Traceback              (most contempo call concluding):   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-15-a5649918d59e>"              , line                            1              , in                            <module>                              raise SyntaxError("Sorry, my error!")                              File                            "<cord>"              , line                            unknown              SyntaxError              :              Lamentable, my fault!            

The best or the Pythonic style to practice this, consists in defining an exception grade which inherits from the Exception class. Y'all volition have to go through the chapter on Object Oriented Programming to fully understand the following instance:

              form              MyException              (              Exception              ):              pass              raise              MyException              (              "An exception doesn't always bear witness the rule!"              )            

OUTPUT:

              ---------------------------------------------------------------------------              MyException              Traceback (most recent call last)              <ipython-input-three-d75bff75fe3a>              in              <module>                              2              laissez passer                              3              ----> 4                                          heighten              MyException(              "An exception doesn't always testify the rule!"              )              MyException: An exception doesn't ever prove the rule!

Clean-up Actions (try ... finally)

So far the try argument had always been paired with except clauses. Only there is some other mode to utilise it as well. The try statement tin be followed past a finally clause. Finally clauses are called clean-up or termination clauses, because they must be executed under all circumstances, i.e. a "finally" clause is ever executed regardless if an exception occurred in a attempt block or not. A simple example to demonstrate the finally clause:

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

OUTPUT:

Your number: 34 There may or may not have been an exception. The inverse:  0.029411764705882353            

Combining try, except and finally

"finally" and "except" can be used together for the aforementioned try block, as it tin can be seen in the following Python example:

              endeavor              :              ten              =              float              (              input              (              "Your number: "              ))              inverse              =              1.0              /              x              except              ValueError              :              print              (              "Yous should have given either an int or a float"              )              except              ZeroDivisionError              :              impress              (              "Infinity"              )              finally              :              print              (              "There may or may not have been an exception."              )            

OUTPUT:

Your number: 23 In that location may or may not have been an exception.            

else Clause

The endeavour ... except statement has an optional else clause. An else block has to exist positioned afterwards all the except clauses. An else clause will be 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              [              one              ]              text              =              []              try              :              fh              =              open              (              file_name              ,              'r'              )              text              =              fh              .              readlines              ()              fh              .              shut              ()              except              IOError              :              print              (              'cannot open'              ,              file_name              )              if              text              :              impress              (              text              [              100              ])            

OUTPUT:

This example receives the file name via a command line argument. So make sure that you telephone call it properly: Let's assume that you saved this program as "exception_test.py". In this example, you lot have to phone call it with

          python exception_test.py integers.txt        

If you don't desire this behaviour, just modify the line "file_name = sys.argv[ane]" to "file_name = 'integers.txt'".

The previous example is nearly the same every bit:

              import              sys              file_name              =              sys              .              argv              [              ane              ]              text              =              []              try              :              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 start case, all statements of the try cake can lead to the aforementioned error bulletin "cannot open up ...", which is wrong, if fh.close() or fh.readlines() enhance an mistake.

Live Python preparation

instructor-led training course

Upcoming online Courses

Intensive Advanced Course

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

Enrol hither

tobinobsomed.blogspot.com

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

0 Response to "Why Does Error Occur When I Read an Int Value From File in While Loop Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel