Chapter 14 - Handling errors Flashcards
Why is notifying the user via a GUI not always the preferred method for
error reporting?
Notifying the user via a GUI assumes that there will always be a human user present to see the message, which is not always the case. Additionally, the user may not be in a position to do anything about the problem, such as in the case of an ATM machine.
this is usually used for errors that the programmer may have control over.
What is the purpose of the
Exception subclass?
What are the two methods provided by the
Files class
to read an entire file?
The two methods provided by this class to read an entire file are lines() and readAllLines().
this is program code that protects statements that may throw an exception.
If an exception is thrown, it can be handled by either creating a report or attempting to recover.
What is an
exception handler?
What are unchecked exceptions in Java?
these are exceptions that would never fail in normal operation, usually indicating some kind of programming error.
These exceptions are not required to be declared in a method’s throws clause, which means that the programmer is not obligated to catch or handle them explicitly.
Examples of unchecked exceptions include calling a method on a null object.
Why is it often harder to find logical errors in a program?
Logical errors cannot be spotted by the compiler unlike syntactical errors and will only show up at some point during runtime.
What are the
natural units to use when reading from files?
The natural units to use when performing this are characters and lines.
This is important in coding because it allows code to warn other code, a human operator, or a programmer that an error has arisen.
This allows the error to be corrected or handled properly, preventing potential issues or vulnerabilities.
Why is
error reporting
important in coding?
this is important in file-based input and output because the programmer has little to no control over the external environment on which the program is run, which means that errors can occur due to various causes, such as required files being deleted or overwritten or corrupted.
Why is
error recovery
important in file-based input and output?
What are unchecked exceptions?
these are exceptions that the compiler enforces few rules on their use, and they are not checked by the compiler.
What are the two subclasses of
Throwable?
subclasses of this include Error and Exception.
How can a
BufferedReader
be created?
this can be created via a static method of Files named NewBufferedReader().
What are the two main categories of classes in the java.io package?
The two main categories of classes in the java.io package are:
- Those that deal with text files (.txt, .html), which are subclasses of the abstract classes Reader and Writer.
- Those that deal with binary files (.png, .exe), which are subclasses of the abstract classes InputStream and OutputStream.
the syntax that allows this is to use the throws keyword in the header followed by comma separarted exceptions
example:
Public void process() throws EOFException, FileNotFoundException
what is the syntax that allows a method or constructor to throw multiple exceptions
What is an example of a
runtime error
that could occur if the code does not implement defensive programming?
An example of this is a null pointer exception, which could occur when we try to call a method on a null object.
This could happen, for example, when we are given an incorrect key and try to access a collection object with that key, such as when removing objects.
What are the 4 steps for saving an object using object serialization? can you write the code?
To accomplish this:
- Ensure the class of the object we wish to save implements the Serializable interface.
- Create an instance of the ObjectOutputStream class, passing in an OutputStream object.
- Call the writeObject() method of the ObjectOutputStream, passing in the object you want to save.
- Close the ObjectOutputStream.
Example:
public void saveToFile(Person person, String destinationFile) { try { // 2. Create an instance of the ObjectOutputStream class, passing in an OutputStream object. FileOutputStream fileOut = new FileOutputStream(destinationFile); ObjectOutputStream out = new ObjectOutputStream(fileOut); // 3. Call the writeObject() method of the ObjectOutputStream, passing in the object you want to save. out.writeObject(person); // 4. Close the ObjectOutputStream. out.close(); } catch (IOException i) { i.printStackTrace(); } }
What is the difference between the next() and nextLine() methods in the Scanner class?
The next() method finds and returns the next complete token from the scanner, while the nextLine() method reads in the next line of text as a string.
Note:
By default, each token is defined as being separated by whitespace, although other separators can be defined.
these include Checked exceptions and unchecked exceptions.
What are the two categories of exception classes in Java?
these may be found in the java.nio.charset package.
What package contains Charsets?
What are the classes in the java.io package that deal with binary files?
The classes in the java.io package that deal with binary files are stream handlers, which are subclasses of the abstract classes InputStream and OutputStream.
for a resource to be able to use the “try with resource” statement what must it implement
in order for a resource to make use of this it must implement the AutoCloseable interface that is defined in the java.lang package.
this is an exception that occurs when we try to access an index that is out of bounds of the operation.
What is an
IndexOutOfBoundsException?
This is a process in programming that aims to prevent errors from occurring as much as possible, in order to avoid the program crashing at runtime and to avoid creating clunky or messy error recovery processes in the client.
What is
error avoidance?
What are the two variant syntax of an assert statement?
syntax includes:
assert booleanExpression;
or
assert booleanExpression : errorMessage;
The second form allows you to provide a custom error message that will be displayed if the assertion fails.
This is a technique used in defensive programming that involves checking that received parameters are valid before carrying out any actions with the data.
What is
parameter checking?
If the program is expected to fail because of this exception, then the calling code cannot do anything, and the program will crash.
However, an exception handler may be written in the calling code to handle the exception.
What happens when an
unchecked exception is thrown?
this is part of the java.io package and is used to hold details of an external file by passing a file name to its constructor. However, it is a legacy class.
What is the
File class
and what package is it part of?
What is the purpose of System.getProperty(“file.encoding”)?
this is used to find the system’s default character encoding.
What are the classes in the java.io package that deal with text files?
The classes in the java.io package that deal with text files are readers and writers, which are subclasses of the abstract classes Reader and Writer.
The readAllLines() method of this class returns a list of all lines from the file.
Note:
this is perhaps preferred over the lines() method when a List is required.
What does the readAllLines() method of the
Files class
return?
What is the general pattern for writing to a file in Java?
describe general steps and write the code
- We usually create a FileWriter object whose constructor takes the name of the file as a string or a File object. The effect of creating a FileWriter is the same as opening the file as the constructor will attempt to open the file and prepare it for receiving data.
- Once a file has been opened we may write to it using the write() method.
- Once all data has been written we must close the file and for this we may use the close() method.
FileWriter writer = new FileWriter(" ... name of file ... " ); while( there is more text to write ) { . . . writer.write( next piece of text ); . . . } writer.close();
What is an
exception object
always an instance of?
this will always be a instance of a class from a special inheritance hierarchy which includes
1. Throwable
2. Error, and Exception.
What are 4 key steps involved in
error recovery?
The key steps involved with this are:
- Using a catch block that contains statements to aid in the recovery process.
- Trying the failed statement again, which usually means being inside a loop such as a do while.
- Implementing a limit on how many times recovery can be attempted, such as a MAX_ATTEMPTS constant.
- Logging the error with any state so that it can be investigated later.
This method in the Scanner class is used to set the scanner’s delimiting pattern to a pattern constructed from the specified string.
What is the
useDelimiter() method
in the Scanner class used for?
these are exceptions that the compiler enforces few rules on their use, and they are not checked by the compiler.
What are unchecked exceptions?
What are the two
steps of throwing an exception?
steps for this include:
1. Creating an exception object using the new keyword.
2. Throwing the exception object using the throw keyword.
What are two general rules to follow when deciding whether to use a checked exception in Java?
general rules for this include:
1.where the programmer may be able to recover if handled appropriately
2.For failure situations beyond the control of the programmer (such as a disk becoming full, such as hardware failures, out of memory errors, or network failures)
Example:
if disk full the client could recover by asking for overwrite or clear disk space
these are statements that are nested inside a try block.
What are
protected statements?
we would define our:
1. checked exceptions as a subclass of Exceptions
2. unchecked exceptions as a subclass of RuntimeExceptions
when defining our own exception classes what would checked exceptions and unchecked exceptions be subclasses of
An example of this is a null pointer exception, which could occur when we try to call a method on a null object.
This could happen, for example, when we are given an incorrect key and try to access a collection object with that key, such as when removing objects.
What is an example of a
runtime error
that could occur if the code does not implement defensive programming?
this class is a checked exception in the java.io package that gives a general indication that an input/output operation has failed.
note:
There are also subclasses of this, such as FileNotFoundException, that offer more detailed diagnostic information.
What is the
IOException class
in java.io package?
What is an
assertion?
An assertion is a statement or fact that should evaluate to true in normal execution at runtime.
this is the third component of the try statement. It is optional and provides a means to execute code regardless of whether an exception is thrown or not.
What is the
finally clause in a try statement?
- We usually create a FileWriter object whose constructor takes the name of the file as a string or a File object. The effect of creating a FileWriter is the same as opening the file as the constructor will attempt to open the file and prepare it for receiving data.
- Once a file has been opened we may write to it using the write() method.
- Once all data has been written we must close the file and for this we may use the close() method.
FileWriter writer = new FileWriter(" ... name of file ... " ); while( there is more text to write ) { . . . writer.write( next piece of text ); . . . } writer.close();
What is the general pattern for writing to a file in Java?
describe general steps and write the code
What is the purpose of the
Exception subclass?
this is usually used for errors that the programmer may have control over.
subclasses of this include Error and Exception.
What are the two subclasses of
Throwable?
What is the hierarchy of exceptions in Java?
All exceptions are subclasses of Throwable, which is in turn a superclass of Error and Exception.
RuntimeException is a subclass of Exception.
An assertion is a statement or fact that should evaluate to true in normal execution at runtime.
What is an
assertion?
What does the lines() method of the
Files class
return?
The lines() method of this class returns the lines of the file as a stream, which can be converted to a string array or placed in an ArrayList<String>
.
Note 1:
conversion can take place using
1. stream.collect
2. Collectors class
Note 2:
This is perhaps preferred over the readAllLines () method for times where a data structure other than a List is required
The two methods provided by this class to read an entire file are lines() and readAllLines().
What are the two methods provided by the
Files class
to read an entire file?
The lines() method of this class returns the lines of the file as a stream, which can be converted to a string array or placed in an ArrayList<String>
.
Note 1:
conversion can take place using
1. stream.collect
2. Collectors class
Note 2:
This is perhaps preferred over the readAllLines () method for times where a data structure other than a List is required
What does the lines() method of the
Files class
return?
this will always be a instance of a class from a special inheritance hierarchy which includes
1. Throwable
2. Error, and Exception.
What is an
exception object
always an instance of?
What is parsing and scanning in Java?
Parsing is the act of identifying an underlying structure, while scanning is the process of piecing individual characters into separate data values.
This class of the java.util package is used to scan text and convert the found characters into typed values such as int or double.
This allows us to read and convert the contents of a file directly and bypass using the BufferedReader.
What is the
Scanner class
used for in Java?
when deciding whether or not to
code defensively
what are two questions the invoked code should ask?
questions the invoked code should ask when deciding to implement this are
1. will calling code always use the API in a proper manner
2. is this code being used in a hostile environment where it may be misusesd
What must a method do in order to compile if it calls another method with a “throws” clause in its header for a checked exception?
If a method calls another method with a “throws” clause in its header for a checked exception, it must either handle the exception or propagate it further in order to compile.
An effective measure used by code to signal that an error has occurred.
It is almost impossible for the calling code to ignore.
describe an
exception
when creating custom exceptions what methods might we include for reporting and recovery by the client
1.A getter method that would allow access to the data causing the error
2.An overriden toString() method that describes the error in full.
The natural units to use when performing this are characters and lines.
What are the
natural units to use when reading from files?
the purpose of this is to declare that a method may throw one or more checked exceptions.
What is the purpose of the
throws clause
in a method header?
describe an
exception
An effective measure used by code to signal that an error has occurred.
It is almost impossible for the calling code to ignore.
when defining our own exception classes what would checked exceptions and unchecked exceptions be subclasses of
we would define our:
1. checked exceptions as a subclass of Exceptions
2. unchecked exceptions as a subclass of RuntimeExceptions
What is the
File class
and what package is it part of?
this is part of the java.io package and is used to hold details of an external file by passing a file name to its constructor. However, it is a legacy class.
what are the 3 methods that could be used by a method that may receive multiple exceptions
in this event the options are:
1. catch each exception independently
example:
Try { Ref.process(); } Catch(EOFException e) { } Catch(FileNotFoundException e ){ }
- use polymorphism using the superclass of all exceptions (Exception) to catch all exceptions. note this comes at an expense of not being able to independenly handle specific exceptions
example:
Try { Ref.process() } Catcth(Exception e) { }
- recommended is to handle multiple exceptions with a single catch block is to use the | (OR) operator
example:
Try { Ref.process(); } Catch(EOFException | FileNotFoundException e) { Take action for each exception }
syntax includes:
assert booleanExpression;
or
assert booleanExpression : errorMessage;
The second form allows you to provide a custom error message that will be displayed if the assertion fails.
What are the two variant syntax of an assert statement?
in this event the effects on the calling code are varied but in general:
if the exception is not caught and handled (reporting, recovery) then the program will terminate and indicate which exception was thrown
This uncovers the power of exceptions that they force the client to handle errors instead of continuing execution
when calling code receives a thrown exception what are the effects
when creating a custom exception what should its constructor take as formal parameters
1.A string that is a message to display
2.The data that actually caused the problem
What is the purpose of
Serializable interface?
This interface is defined in the java.io package and acknowledges that the object may be serialized and deserialized.
It allows objects to participate in serialization and deserialization processes.
The process of serialization is carried out by the Java runtime system, and very little code needs to be written by the programmer.
describe the static method
Objects.requireNonNull(Object obj, String message).
this is part of the java.utils.Objects package
it is used to ensure that an object passed as an argument is not null. If the object is null, then it will throw a NullPointerException with the given message
What is the purpose of the
Error subclass?
this is usually used for runtime system errors (errors the programmer may have no control over), and the program would usually be allowed to terminate.
general rules for this include:
1.for for situations that should lead to program failure such as programming errors, bugs, or unexpected situations that the program cannot handle
2.For situations that could reasonably be avoided (such as calling a method on a null object)
What are some general rules to follow when deciding whether to use a unchecked exception in Java?
What is thrown in the following code?
throw new IllegalArgumentException(“null parameter received”)
A new IllegalArgumentException object with the message “null parameter received.”
What is an
IndexOutOfBoundsException?
this is an exception that occurs when we try to access an index that is out of bounds of the operation.
Can the FileReader class read lines?
No, FileReader cannot read lines by itself.
the Filereader class main use is for reading in chracters.