How to Try to Get Input Again After Exception Java

Object-Oriented Programming with Java, part I + II

cc

This material is licensed nether the Creative Commons Past-NC-SA license, which means that you lot can employ it and distribute information technology freely so long every bit you lot practice non erase the names of the original authors. If yous make changes in the material and want to distribute this altered version of the material, you accept to license it with a similar free license. The employ of the material for commercial use is prohibited without a dissever understanding.

Authors: Arto Hellas, Matti Luukkainen
Translators to English language: Emilia Hjelm, Alex H. Virtanen, Matti Luukkainen, Virpi Sumu, Birunthan Mohanathas, Etiënne Goossens
Extra textile added by: Etiënne Goossens, Maurice Snoeren, Johan Talboom

The class is maintained by De Haagse Hogeschool


7. Input/output and exception handling

7.1 Exceptions

Exceptions are such situations where the program executions is different from our expectations. For instance, the program may accept called a method of a nil reference, in which case the user is thrown a NullPointerException. If we try to retrieve a index outside a table, the user is thrown a IndexOutOfBoundsException. All of them are a blazon of Exception.

Exceptions are often caused by unexpected situations that occur when treatment input and output of a program. For example: users can easily frustrate a plan by entering input in an unexpected format.

We deal with exceptions by using the block try { } catch (Exception e) { }. The lawmaking independent within the brackets which follows the keyword try will not crash when an exception occurs in this part of the code. The code within the brackets which follow the keyword grab defines what should happen when the try-code throws an exception. We also ascertain the blazon of the exception we want to catch (grab (Exception due east)).

                          try              {              // lawmaking which can throw an exception              }              catch              (              Exception              east              )              {              // code which is executed in case of exception              }                      

The parseInt method of class Integer which turns a string into a number can throw a NumberFormatException if its string parameter cannot be turned into a number. At present we implement a program that turns a user input Cord to a number.

                          Scanner              reader              =              new              Scanner              (              System              .              in              );              System              .              out              .              impress              (              "Write a number: "              );              int              num              =              Integer              .              parseInt              (              reader              .              nextLine              ());                      
          Write a number: ~~tatti~~ ~~Exception in thread "..." java.lang.NumberFormatException: For input string: "tatti"~~                  

The program above throws an exception because the user digits an erroneous number. The program execution ends upward with a malfunction, and it cannot continue. We add together an exception management statement to our program. The call, which may throw an exception is written into the try block, and the action which takes place in instance of exception is written into the catch block.

                          Scanner              reader              =              new              Scanner              (              System              .              in              );              System              .              out              .              impress              (              "Write a number: "              );              try              {              int              num              =              Integer              .              parseInt              (              reader              .              nextLine              ());              }              catch              (              Exception              eastward              )              {              System              .              out              .              println              (              "You haven't written a proper number."              );              }                      
          Write number: ~~5~~                  
          Write number: ~~oh no!~~ You haven't written a proper number.                  

In case of exception, nosotros move from the chunk of code defined by the try keyword to the catch chunk. Permit's run across this past adding a impress argument afterward the Integer.parseInt line in the try clamper.

                          Scanner              reader              =              new              Scanner              (              Organisation              .              in              );              System              .              out              .              print              (              "Write a number: "              );              try              {              int              num              =              Integer              .              parseInt              (              reader              .              nextLine              ());              System              .              out              .              println              (              "Looks good!"              );              }              grab              (              Exception              e              )              {              System              .              out              .              println              (              "Yous oasis't written a proper number."              );              }                      
          Write a number: ~~5~~ Looks proficient!                  
          Write a number: ~~I won't!~~ you haven't written a proper number.                  

String I won't! is given equally parameter to the method Integer.parseInt, which throws an exception if the String parameter tin can't be changed into a number. Note that the code in the catch clamper is executed just in example of exception – otherwise the programme practice not make it till in that location.

Allow's make something more useful out of our number translator: let'southward practice a method which keeps on asking to type a number till the user does it. The user tin can return only if they have typed the right number.

                          public              int              readNumber              (              Scanner              reader              )              {              boolean              running              =              true              ;              while              (              running              )              {              System              .              out              .              print              (              "Write a number: "              );              try              {              int              num              =              Integer              .              parseInt              (              reader              .              nextLine              ());              return              num              ;              }              grab              (              Exception              e              )              {              System              .              out              .              println              (              "Y'all oasis't written a proper number."              );              }              }              }                      

The method readNumber could work in the following way:

          Write a number: ~~I won't!~~ Y'all haven't written a proper number. Write a number: ~~Matti has a mushroom on his door.~~ You haven't written a proper number. Write a number: ~~43~~                  

seven.1.1 Throwing Exceptions

Methods and constructors tin throw exceptions. So far, in that location are two kinds of exceptions which can be thrown. At that place are the ones which have to be handled, and the ones which don't have to be dealt with. When we take to handle the exceptions, we do it either in a endeavor-take hold of chunk, or throwing them from a method.

In the clock practise of Introduction to Programming (not in the HHS-grade), we explained that we tin can stop our plan of ane second, by calling the method Thread.sleep(k). The method may throw an exception, which we must bargain with. In fact, we handle the exception using the try-catch judgement; in the post-obit example we skip the exception, and we leave empty the take hold of chunk.

                          try              {              // we sleep for 1000 milliseconds              Thread              .              sleep              (              1000              );              }              catch              (              Exception              due east              )              {              // In case of exception, we do not exercise anything.              }                      

It is also possible to avert handling the exceptions in a method, and consul the responsibility to the method caller. We delegate the responsibility of a method past using the argument throws Exception.

                          public              void              slumber              (              int              sec              )              throws              Exception              {              Thread              .              slumber              (              sec              *              k              );              // now we don't need the try-catch cake              }                      

The sleep method is called in another method. Now, this other method can either handle the exception in a try-catch cake or delegate the responsibleness forward. Sometimes, we delegate the responsibleness of treatment an exception till the very end, and even the primary method delegates it:

                          public              class              Principal              {              public              static              void              main              (              String              []              args              )              throws              Exception              {              // ...              }              }                      

In such cases, the exception ends upwards in Java's virtual machine, which interrupts the program in case in that location is an error which causes the problem.

There are some exceptions which the programmer does not always accept to address, such as the NumberFormatException which is thrown by Integer.parseInt. Also the RuntimeExceptions do not always require to be addressed. These are ii examples of exceptions that don't have to be dealt with. The compiler cannot 'predict' that an exception will occur, and so it does not force yous to catch the exception.

Nosotros can throw an exception by using the throw argument. For case, if we desire to throw an exception which was created in the class NumberFormatException, we could use the statement throw new NumberFormatException().

Another exception which hasn't got to be addressed is IllegalArgumentException. With IllegalArgumentException we know that a method or a constructor has received an illegal value as parameter. For case, we use the IllegalArgumentException when we want to make sure that a parameter has received particular values.

In the example below nosotros have the constructor public Form(int grade). A constructor is a special method that volition be explained afterward on when we innovate classes. For now you tin can consider it every bit a 'regular' method that expects parameters like whatever other method.

                          public              class              Grade              {              private              int              form              ;              public              Grade              (              int              grade              )              {              this              .              course              =              form              ;              }              public              int              getGrade              ()              {              return              this              .              grade              ;              }              }                      

Next, we desire to validate the value of the constructor parameter of our Grade class. The grades in Finland are from 0 to v. If the grade is something else, we want to throw an exception. We can add an if argument to our Grade form constructor, which checks whether the grade is exterior range 0-5. If then, we throw an IllegalArgumentException telling throw new IllegalArgumentException("The course has to be between 0-5");.

                          public              class              Course              {              private              int              form              ;              public              Course              (              int              grade              )              {              if              (              class              <              0              ||              form              >              5              )              {              throw              new              IllegalArgumentException              (              "The grade has to exist between 0-5"              );              }              this              .              grade              =              grade              ;              }              public              int              getGrade              ()              {              return              this              .              grade              ;              }              }                      
                          Grade              course              =              new              Grade              (              3              );              System              .              out              .              println              (              class              .              getGrade              ());              Class              wrongGrade              =              new              Form              (              22              );              // it causes an exception, we don't continue                      
          3 Exception in thread "..." java.lang.IllegalArgumentException: The grade has to exist betwixt 0-5                  

7.1.2 The Exception Information

The take hold of cake tells how we handle an exception, and it tells us what exception nosotros should exist prepared for: take hold of (Exception e). The exception information is saved into the e variable.

                          try              {              // the code, which may throw an exception              }              catch              (              Exception              due east              )              {              // the exception information is saved into the variable e              }                      

The class Exception can provide useful methods. For example, the method printStackTrace() prints a path which tells us where the exception came from. Allow's check the following error printed by the method printStackTrace().

          Exception in thread "main" java.lang.NullPointerException   at package.Class.print(Class.java:43)   at packet.Class.master(Class.coffee:29)                  

Reading the stack trace happens button upwardly. The everyman is the first telephone call, i.e. the program execution has started from the primary() method of class Class. At line 29 of the main method of Class, we chosen the method impress(). Line 43 of the method print caused a NullPointerException. Exception data are extremely important to find out the origin of a trouble.

Exercise v-ane: Method Argument Validation

Let'due south train method argument validation with the help of the IllegalArgumentException. The excercise layout shows 2 classes Person and Reckoner. Change the grade in the following style:

Exercise five-1.one: Person Validation

The constructor of Person has to make sure its parameter's proper noun variable is non null, empty, or longer than twoscore characters. The age has also to be between 0-120. If one of the conditions above are not satisfied, the constructor has to throw an IllegalArgumentException.

Practice 5-i.ii: Figurer Validation

The Computer methods have to be changed in the following manner: the method multiplication has to work only if its parameter is not negative (greater than or equal to 0). The method binomialCoefficient has to work only if the parameters are not negative and the size of a subset is smaller than the set'southward size. If one of the methods receives invalid arguments when they are called, they accept to throw a IllegalArgumentException.

Exercise 5-1.3: Exception handling

The main method crashes when an IllegalArgumentException is thrown. Add proper exception treatment and then that the principal method does not crash whatsoever more. Print the exception data, and so that the program shows what goes incorrect. NB: This office of the practise is non verified automatically.

vii.2 Reading from a file

A relevant role of programming is related to stored files, in one way or in another. Let's accept the beginning steps in Java file handling. Java's API provides the course File, whose contents tin be read using the already known Scanner course.

If we read the desciption of the File API we detect the File class has the constructor File(String pathname), which creates a new File instance by converting the given pathname string into an abstract pathname. This ways the File class constructor can be given the pathname of the file we want to open up.

In the programming surroundings, files accept got their own tab called Files, which contains all our project files. If we add a file to a project root – that is to say outside all folders – we tin refer to information technology by writing simply the its proper name. We create a file object past giving the file pathname to it as parameter:

                          File              file              =              new              File              (              "file-name.txt"              );                      

The Organization.in input stream is not the but reading source we tin can requite to the constructor of a Scanner course. For instance, the reading source tin be a file, in addition to the user keyboard. Scanner provides the aforementioned methods to read a keyboard input and a file. In the following example, nosotros open a file and we print all the text independent in the file using the System.out.println argument. At the end, we shut the file using the statement close.

                          // The file we read              File              file              =              new              File              (              "filename.txt"              );              Scanner              reader              =              new              Scanner              (              file              );              while              (              reader              .              hasNextLine              ())              {              String              line              =              reader              .              nextLine              ();              System              .              out              .              println              (              line              );              }              reader              .              close              ();                      

The Scanner class constructor public Scanner(File source) (Constructs a new Scanner that produces values scanned from the specified file.) throws a FileNotFoundException when the specified file is not found. The FileNotFoundException is different than RuntimeException, and nosotros have either to handle information technology or throw it forwards. At this indicate, you but accept to know that the programming surround tells y'all whether you have to handle the exception or not. Permit'southward first create a try-catch block where nosotros handle our file as shortly equally we open it.

                          public              void              readFile              (              File              f              )              {              // the file we read              Scanner              reader              =              naught              ;              try              {              reader              =              new              Scanner              (              f              );              }              take hold of              (              Exception              e              )              {              System              .              out              .              println              (              "We couldn't read the file. Error: "              +              east              .              getMessage              ());              return              ;              // we get out the method              }              while              (              reader              .              hasNextLine              ())              {              Cord              line              =              reader              .              nextLine              ();              System              .              out              .              println              (              line              );              }              reader              .              close              ();              }                      

Some other option is to consul the exception handling responsibleness to the method caller. We delegate the exception handling responsibility past adding the definition throws ExceptionType to the method. For instance, we can add together throws Exception because the type of all exceptions is Exception. When a method has the aspect throws Exception, any chunk of code which calls that method knows that it may throw an exception, and it should be prepared for it.

                          public              void              readFile              (              File              f              )              throws              Exception              {              // the file we read              Scanner              reader              =              new              Scanner              (              f              );              while              (              reader              .              hasNextLine              ())              {              String              line              =              reader              .              nextLine              ();              System              .              out              .              println              (              line              );              }              reader              .              shut              ();              }                      

In the case, the method readFile receives a file as parameter, and prints all the file lines. At the end, the reader is closed, and the file is closed with it, too. The attribute throws Exception tells usa that the method may throw an exception. Same kind of attributes tin be added to all the methods that handle files.

Note that the Scanner object'south method nextLine returns a string, but information technology does not render a new line at the terminate of information technology. If you want to read a file and still maintain the new lines, you tin add a new line at the finish of each line:

                          public              Cord              readFileString              (              File              f              )              throws              Exception              {              // the file we read              Scanner              reader              =              new              Scanner              (              f              );              Cord              cord              =              ""              ;              while              (              reader              .              hasNextLine              ())              {              String              line              =              reader              .              nextLine              ();              string              +=              line              ;              cord              +=              "\n"              ;              }              reader              .              close              ();              return              string              ;              }                      

Because we utilise the Scanner class to read files, we have all Scanner methods bachelor for use. For instance the method hasNext() returns the boolean value true if the file contains something more to read, and the method next() reads the following discussion and returns a String object.

The following program creates a Scanner object which opens the file file.txt. Then, information technology prints every 5th word of the file.

                          File              f              =              new              File              (              "file.txt"              );              Scanner              reader              =              new              Scanner              (              f              );              int              whichNumber              =              0              ;              while              (              reader              .              hasNext              ())              {              whichNumber              ++;              String              give-and-take              =              reader              .              side by side              ();              if              (              whichNumber              %              5              ==              0              )              {              System              .              out              .              println              (              word              );              }              }                      

Below, you find the text contained in the file, followed past the program output.

          Exception handling is the process of responding to the occurrence, during ciphering, of exceptions – anomalous or exceptional events   requiring special processing – often changing the normal catamenia of program execution. ...                  
          process occurrence, – requiring changing program                  

vii.2.1 Character Set Issues

When we read a text file (or when we salvage something into a file), Java has to find out the graphic symbol set used by the operating system. Knowledge of the character set is required both to salvage text on the calculator harddisk in binary format, and to translate binary data into text.

There have been developed standard grapheme sets, and "UTF-8" is the well-nigh common nowadays. UTF-eight character set contains both the alphabet messages of everyday use and more particular characters such as the Japanese kanji characters or the data need to read and relieve the chess pawns. From a simplified programming angle, we could think a character set both every bit a graphic symbol-number hashmap and a number-character hashmap. The character-number hashmap shows what binary number is used to save each character into a file. The number-grapheme hashmap shows how nosotros tin can interpret into characters the values nosotros obtain reading a file.

Almost each operating system producer has also got their own standards. Some support and want to contribute to the use of open up source standards, some do not. If you have got problems with the employ of Scandinavian characters such every bit ä and ö (expecially Mac and Windows users), you tin can tell which graphic symbol set you want to employ when you create a Scanner object. In this class, we always utilize the the "UTF-8" character prepare.

Yous tin can create a Scanner object which to read a file which uses the UTF-8 character set in the following manner:

                          File              f              =              new              File              (              "examplefile.txt"              );              Scanner              reader              =              new              Scanner              (              f              ,              "UTF-8"              );                      

Anther thing you tin can do to set upward a grapheme prepare is using an environment variable. Macintosh and Windows users tin can set upwardly an the value of the environment variable JAVA_TOOL_OPTIONS to the string -Dfile.encoding=UTF8. In such case, Coffee ever uses UTF-8 characters as a default.

Exercise 5-2: Printer

Fill up in the gaps in the class Printer

It has a constructor public Printer(String t) which receives a String standing for the file name. Information technology opens the file, reads all the lines and puts them into an ArrayList.

The method public void printLinesWhichContain(String word) loops through the ArrayList and prints the lines that contain the word that is passed equally a parameter. The lines are printed in the same club as they are inside the file. (lower and upper case make difference in this excercise; for instance, "test" and "Test" are not the considered equal);

If the argument is an empty Cord, all of the file is printed.

If the file is not found, the method delegates the exception with no demand for a try-catch statement; the method simply has to be defined in the following way:

                                  public                  Printer                  {                  public                  Printer                  (                  String                  t                  )                  throws                  Exception                  {                  // ...                  }                  // ...                  }                              

The file textFile has been identify into the default package of your project to assistance the tests. When you define the file proper noun of the constructor of Printer, you lot have to write src/textfile.txt. The file contains an extract of Kalevala, a Finnish ballsy poem:

              Siinä vanha Väinämöinen katseleikse käänteleikse Niin tuli kevätkäkönen näki koivun kasvavaksi Miksipä on tuo jätetty koivahainen kaatamatta Sanoi vanha Väinämöinen                          

The following instance shows what the program should do:

                                  Printer                  printer                  =                  new                  Printer                  (                  "src/textfile.txt"                  );                  printer                  .                  printLinesWhichContain                  (                  "Väinämöinen"                  );                  System                  .                  out                  .                  println                  (                  "-----"                  );                  printer                  .                  printLinesWhichContain                  (                  "Frank Zappa"                  );                  Organization                  .                  out                  .                  println                  (                  "-----"                  );                  printer                  .                  printLinesWhichContain                  (                  ""                  );                  Organisation                  .                  out                  .                  println                  (                  "-----"                  );                              

Prints:

              Siinä vanha Väinämöinen Sanoi vanha Väinämöinen ----- ----- Siinä vanha Väinämöinen katseleikse käänteleikse Niin tuli kevätkäkönen näki koivun kasvavaksi Miksipä on tuo jätetty koivahainen kaatamatta Sanoi vanha Väinämöinen                          

In the project, you also discover the whole Kalevala; the file name is src/kalevala.txt

Exercise v-three: File Analysis

In this exercise, we create an application to calculate the number of lines and characters.

Implement the method readFile(). Read the file using a scanner and suspend all the lines to the variable 'str'. Add together a 'new line' grapheme at then end of every line.

Y'all tin decide yourself what to do if the constructor parameter file does not exist.

The file testFile has been place into the test bundle of your project to help the tests. When you lot define the file proper noun of the constructor of Assay, you take to write test/testfile.txt. The file contains the following text:

              there are three lines, and characters considering line breaks are also characters                          

The post-obit instance shows what the program should exercise:

                                  File                  file                  =                  new                  File                  (                  "examination/testfile.txt"                  );                  Analysis                  analysis                  =                  new                  Analysis                  (                  file                  );                  System                  .                  out                  .                  println                  (                  "Lines: "                  +                  assay                  .                  lines                  ());                  Organisation                  .                  out                  .                  println                  (                  "Characters: "                  +                  analysis                  .                  characters                  ());                              
              Lines: 3 Characters: 74                          

seven.3 Writing a File

In section 12.one, we learnt that reading from a file happened with the help of the classes Scanner and File. The class FileWriter provides the functionality to write to a file. The FileWriter constructor is given equally parameter a String illustrating the file location.

                          FileWriter              writer              =              new              FileWriter              (              "file.txt"              );              author              .              write              (              "Hullo file!\northward"              );              // the line break has to be written, too!              author              .              write              (              "Adding text\n"              );              writer              .              write              (              "And more"              );              writer              .              close              ();              // the call closes the file and makes sure the written text goes to the file                      

In the example nosotros write the string "How-do-you-do file!" to the file "file.txt"; that is followed by a line interruption, and by more text. Note that when yous use the write method, information technology does not produce line breaks, but they have to be added afterwards manually.

Both the FileWriter constructor and the write method may throw an exception, which has to be either handled or the responsibility has to be delegated to the calling method. The method which is given every bit parameter the file name and the text to write into it can await like the following.

                          public              class              FileHandler              {              public              void              writeToFile              (              Cord              fileName              ,              String              text              )              throws              Exception              {              FileWriter              writer              =              new              FileWriter              (              fileName              );              writer              .              write              (              text              );              writer              .              close              ();              }              }                      

In the higher up method writeToFile, we commencement create a FileWriter object, which writes into the fileName file stored at the location specified every bit parameter. Later this, we write into the file using the write method. The exception the constructor and write method can peradventure throw has to be handled either with the help of a endeavor-take hold of block or delegating the responsibility. In the method writeToFile the responsibility was delegated.

Let's create a primary method where we call the writeToFile method of a FileHandler object. The exception does not have to exist handled in the primary method either, but the method tin can declare to throw possibly an exception throw the definition throws Exception.

                          public              static              void              main              (              Cord              []              args              )              throws              Exception              {              FileHandler              handler              =              new              FileHandler              ();              handler              .              writeToFile              (              "diary.txt"              ,              "Dear Diary, today was a nice solar day."              );              }                      

When we phone call the method higher up, we create the file "diary.txt", where nosotros write the text "Love Diary, today was a nice twenty-four hours.". If the file exists already, the old content is erased and the new one is written. FileWriter allows us to add text at the end of the already existing file by providing additional parameter boolean append, without erasing the existing text. Let'south add together the method appendToFile() to the form FileHandler; the method appends the text received every bit parameter to the stop of the file.

                          public              course              FileHandler              {              public              void              writeToFile              (              String              fileName              ,              Cord              text              )              throws              Exception              {              FileWriter              author              =              new              FileWriter              (              fileName              );              author              .              write              (              text              );              author              .              shut              ();              }              public              void              appendToFile              (              String              fileName              ,              String              text              )              throws              Exception              {              FileWriter              writer              =              new              FileWriter              (              fileName              ,              truthful              );              writer              .              write              (              text              );              author              .              close              ();              }              }                      

In most of the cases, instead of writing text at the end of a file with the method append, it is easier to write all the file over again.

Exercise 5-four: File Manager

Together with the practice body, you lot find the class FileManager, which contains the method bodies to read a write a file.

Practise five-4.1: File Reading

Implement the method public ArrayList<String> read(String file) to return the lines of the parameter file in ArrayList class, each file line existence a String contained by the ArrayList.

In that location are two text files to help testing the project: src/testinput1.txt and src/testinput2.txt. The methods are supposed to exist used in the following manner:

                                  public                  static                  void                  master                  (                  String                  []                  args                  )                  throws                  FileNotFoundException                  ,                  IOException                  {                  FileManager                  f                  =                  new                  FileManager                  ();                  for                  (                  Cord                  line                  :                  f                  .                  read                  (                  "src/testinput1.txt"                  ))                  {                  Arrangement                  .                  out                  .                  println                  (                  line                  );                  }                  }                              

The print output should look like the following

              showtime 2nd                          

Exercise 5-four.2: Writing a Line

Modify the method public void save(String file, String text) and so that it writes the String text into the file. If the file already exists, overwrite its contents.

Practise 5-4.3: Writing an ArrayList

Modify the method public void salvage(Cord file, ArrayList<String> texts) so that it writes the content of the ArrayList texts into the file. If the file already exists, overwrite its contents.


end of calendar week five

turnerfirelp1967.blogspot.com

Source: https://hhs-2018-se-dt-s2-apip.github.io/lesmateriaal/week5

0 Response to "How to Try to Get Input Again After Exception Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel