CS201 - Spring 2014 - Class 11
Exercises
Assignment part 1
Admin
- Assignment 4 part 2 out this afternoon
- back to working on your own
- finish one piece at a time (specifically one method)
- debugging
run GuessingGameWithProblem in
GuessingGame code
look at GuessingGameWithProblem in
GuessingGame code
- Is there anything that the user could do while playing the game to cause a problem?
- if the user enters something that is not a number!
- What do you think happens when the user enters something that is not a number?
- We get an Exception!
Exceptions
- What exceptions have you seen already?
- ClassCastException
- NullPointerException
- ArrayIndexOutOfBoundsException
- StringIndexOutOfBoundsException
- Exceptions may seem like errors (and they are), but they're also another way for a method to communicate to whoever calls it
- return allows it to return a value
- throwing an Exception tells whoever called the method that something went wrong
try-catch blocks
- If you want to program to stop when an Exception is thrown, you don't have to do anything (as you've noticed)
- If you want to try and handle a problem and NOT have the program stop, you can "catch" an Exception
- Syntax:
try{
// code that might throw an Exception
} catch (exception_class_name variable_name){
// code to run if an exception of type exception_class_name occurs in the try block above
}
- When the code is run, if no Exception occurs, then the catch block is skipped
- If an Exception of the type exception_class_name occurs in the try block of code, then the code jumps immediately down to catch block, executes the code in there and then continues on after the block
Can we use this to help us solve our problem with the guessing game?
Look at GuessingGame in
GuessingGame code
- We've surrounded the while loop code with a try-catch block
- If the user enters a number, everything works as before
- If the user enters something that is not a number, then the in.nextInt() call will throw an Exception
- It will skip the if/else if/else block of code and go immediately to the catch block
- It will then print out that there was an issue
- The scanner class buffers the input and so it still has that string sitting there. We have to read the string and ignore it.
- The loop will then continue as normal
run GradeGeneratorPrint in
GradeGenerator code
- reads in a list of names from a file
- generates a grade for each name in the file
Reading from files
- There are many ways to read data from files (we'll see 2 today)
- One is to use the Scanner class
Given a String with a filename:
Scanner in = new Scanner(new File(filename));
- Same Scanner class/interface we were using before except now we created it to read from a file instead of from System.in (from the user)
Checked Exceptions
- Could anything go wrong when opening a file like this? Put another way, what Exceptions could occur?
- If you just try and open the scanner like this, Java will complain
- Some Exceptions are called "checked" Exceptions
- checked Exceptions MUST be handled
- we must wrap the statement that could throw that Exception in a try-catch block
If you try and do the above line for creating a Scanner from a file, you'll get a compilation error
"Unhandled Exception"
- Opening a file can generate a FileNotFoundException which is a checked exception, so we have to put it in a try-catch block
look at GradeGeneratorPrint in
GradeGenerator code
\t
- there are a few "special" characters that we might want in strings
- these are generally indicated by preceding them with a \
\t: tab
\n: end of line
- there are a few others, but these are the most common
File system
Writing to files
- Printing the grades list is nice, but in some situations it would be better to print it to a file
- As with reading from files, there are many ways to do it
- One easy way is with the PrintWriter class
PrintWriter out = new PrintWriter(new FileOutputStream(outfilename));
- PrintWriter has a similar interface to the System.out, in particular, it has a method called out.println()
- the difference is that it prints it out to the file
- When you're done writing to a file, *** don't forget to close it ***
- Do you think opening a file for writing throws any Exceptions?
- Yes! FileNotFoundException
run and look at GradeGeneratorFile in
GradeGenerator code
- looks almost the same, except we create a PrintWriter and use that instead of System.out
- Why do I only have one try-catch block?
- the catch statement will catch *any* Exception of that type in the try block
- What's different about the code in the catch statement?
- Before, there was only one file that could be the offending file being opened
- Now, it could be either the file being read from or the file being written to
Exceptions are classes!
- they have methods, etc.
- When an exception is thrown/generated, a new exception object is generated
- The two most common methods you might want to call is:
- e.getMessage()
- get (as a String) a detailed messaged about this exception
- e.printStackTrace()
- prints out the normal thing you see with the hierarchy of method calls that led to the exception being thrown
Look at GradeGeneratorFileBufferedReader
- BufferedReader is another class that allows us to read from files (well, really the FileReader class)
- It has less bells and whistles than the scanner class
- it doesn't support things like nextInt, nextFloat, etc.
- the most common method that you'll call is readLine(), which reads the next line of the file and returns it as a String
- when the file is out of data, this method returns null
- so the general form of a loop is something like:
read a line
while that line isn't null
do some stuff
read another line
IOException
- When you open a FileReader(i.e. BufferedReader) it can throw a FileNotFoundException
- When you read from a BufferedReader it can throw an IOException, which is a type Exception
- I've only caught the IOException. Why is Java letting me do this?
- IOException is a superclass of FileNotFoundException!
Exception hierarchy
- There are a lot of Exceptions!
- All Exceptions, inherit from the class Exception
- it's kind of like Object for Exceptions (though remember that Exceptions are classes and actually do inherit from Object)
- If you put:
catch(Exception e){
}
- you will catch *ALL* exceptions that are thrown!
- however, it's better style to specifically list the Exception you're trying to catch