Chapter 14 - Handling errors Flashcards

1
Q

Why is notifying the user via a GUI not always the preferred method for
error reporting?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

this is usually used for errors that the programmer may have control over.

A

What is the purpose of the
Exception subclass?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the two methods provided by the
Files class
to read an entire file?

A

The two methods provided by this class to read an entire file are lines() and readAllLines().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

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.

A

What is an
exception handler?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are unchecked exceptions in Java?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Why is it often harder to find logical errors in a program?

A

Logical errors cannot be spotted by the compiler unlike syntactical errors and will only show up at some point during runtime.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are the
natural units to use when reading from files?

A

The natural units to use when performing this are characters and lines.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

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.

A

Why is
error reporting
important in coding?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

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.

A

Why is
error recovery
important in file-based input and output?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are unchecked exceptions?

A

these are exceptions that the compiler enforces few rules on their use, and they are not checked by the compiler.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are the two subclasses of
Throwable?

A

subclasses of this include Error and Exception.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How can a
BufferedReader
be created?

A

this can be created via a static method of Files named NewBufferedReader().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are the two main categories of classes in the java.io package?

A

The two main categories of classes in the java.io package are:

  1. Those that deal with text files (.txt, .html), which are subclasses of the abstract classes Reader and Writer.
  2. Those that deal with binary files (.png, .exe), which are subclasses of the abstract classes InputStream and OutputStream.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

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

A

what is the syntax that allows a method or constructor to throw multiple exceptions

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is an example of a
runtime error
that could occur if the code does not implement defensive programming?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What are the 4 steps for saving an object using object serialization? can you write the code?

A

To accomplish this:

  1. Ensure the class of the object we wish to save implements the Serializable interface.
  2. Create an instance of the ObjectOutputStream class, passing in an OutputStream object.
  3. Call the writeObject() method of the ObjectOutputStream, passing in the object you want to save.
  4. 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();
        }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is the difference between the next() and nextLine() methods in the Scanner class?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

these include Checked exceptions and unchecked exceptions.

A

What are the two categories of exception classes in Java?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

these may be found in the java.nio.charset package.

A

What package contains Charsets?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What are the classes in the java.io package that deal with binary files?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

for a resource to be able to use the “try with resource” statement what must it implement

A

in order for a resource to make use of this it must implement the AutoCloseable interface that is defined in the java.lang package.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

this is an exception that occurs when we try to access an index that is out of bounds of the operation.

A

What is an
IndexOutOfBoundsException?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

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.

A

What is
error avoidance?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What are the two variant syntax of an assert statement?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

This is a technique used in defensive programming that involves checking that received parameters are valid before carrying out any actions with the data.

A

What is
parameter checking?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

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.

A

What happens when an
unchecked exception is thrown?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

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.

A

What is the
File class
and what package is it part of?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What is the purpose of System.getProperty(“file.encoding”)?

A

this is used to find the system’s default character encoding.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What are the classes in the java.io package that deal with text files?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

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.

A

What does the readAllLines() method of the
Files class
return?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What is the general pattern for writing to a file in Java?

describe general steps and write the code

A
  1. 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.
  2. Once a file has been opened we may write to it using the write() method.
  3. 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();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What is an
exception object
always an instance of?

A

this will always be a instance of a class from a special inheritance hierarchy which includes
1. Throwable
2. Error, and Exception.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What are 4 key steps involved in
error recovery?

A

The key steps involved with this are:

  1. Using a catch block that contains statements to aid in the recovery process.
  2. Trying the failed statement again, which usually means being inside a loop such as a do while.
  3. Implementing a limit on how many times recovery can be attempted, such as a MAX_ATTEMPTS constant.
  4. Logging the error with any state so that it can be investigated later.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

This method in the Scanner class is used to set the scanner’s delimiting pattern to a pattern constructed from the specified string.

A

What is the
useDelimiter() method
in the Scanner class used for?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

these are exceptions that the compiler enforces few rules on their use, and they are not checked by the compiler.

A

What are unchecked exceptions?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

What are the two
steps of throwing an exception?

A

steps for this include:
1. Creating an exception object using the new keyword.
2. Throwing the exception object using the throw keyword.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

What are two general rules to follow when deciding whether to use a checked exception in Java?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

these are statements that are nested inside a try block.

A

What are
protected statements?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

we would define our:
1. checked exceptions as a subclass of Exceptions
2. unchecked exceptions as a subclass of RuntimeExceptions

A

when defining our own exception classes what would checked exceptions and unchecked exceptions be subclasses of

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
A

ignore

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

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.

A

What is an example of a
runtime error
that could occur if the code does not implement defensive programming?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

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.

A

What is the
IOException class
in java.io package?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

What is an
assertion?

A

An assertion is a statement or fact that should evaluate to true in normal execution at runtime.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

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.

A

What is the
finally clause in a try statement?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q
  1. 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.
  2. Once a file has been opened we may write to it using the write() method.
  3. 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();
A

What is the general pattern for writing to a file in Java?

describe general steps and write the code

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

What is the purpose of the
Exception subclass?

A

this is usually used for errors that the programmer may have control over.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

subclasses of this include Error and Exception.

A

What are the two subclasses of
Throwable?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

What is the hierarchy of exceptions in Java?

A

All exceptions are subclasses of Throwable, which is in turn a superclass of Error and Exception.

RuntimeException is a subclass of Exception.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

An assertion is a statement or fact that should evaluate to true in normal execution at runtime.

A

What is an
assertion?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

What does the lines() method of the
Files class
return?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

The two methods provided by this class to read an entire file are lines() and readAllLines().

A

What are the two methods provided by the
Files class
to read an entire file?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

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

A

What does the lines() method of the
Files class
return?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

this will always be a instance of a class from a special inheritance hierarchy which includes
1. Throwable
2. Error, and Exception.

A

What is an
exception object
always an instance of?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

What is parsing and scanning in Java?

A

Parsing is the act of identifying an underlying structure, while scanning is the process of piecing individual characters into separate data values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

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.

A

What is the
Scanner class
used for in Java?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

when deciding whether or not to
code defensively
what are two questions the invoked code should ask?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

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?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

An effective measure used by code to signal that an error has occurred.

It is almost impossible for the calling code to ignore.

A

describe an
exception

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

when creating custom exceptions what methods might we include for reporting and recovery by the client

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q

The natural units to use when performing this are characters and lines.

A

What are the
natural units to use when reading from files?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

the purpose of this is to declare that a method may throw one or more checked exceptions.

A

What is the purpose of the
throws clause
in a method header?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

describe an
exception

A

An effective measure used by code to signal that an error has occurred.

It is almost impossible for the calling code to ignore.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q

when defining our own exception classes what would checked exceptions and unchecked exceptions be subclasses of

A

we would define our:
1. checked exceptions as a subclass of Exceptions
2. unchecked exceptions as a subclass of RuntimeExceptions

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
64
Q

What is the
File class
and what package is it part of?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
65
Q

what are the 3 methods that could be used by a method that may receive multiple exceptions

A

in this event the options are:
1. catch each exception independently

example:

Try {
   Ref.process();
}
Catch(EOFException e) {
}
Catch(FileNotFoundException e ){
}
  1. 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) {
}
  1. 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
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
66
Q

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.

A

What are the two variant syntax of an assert statement?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
67
Q

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

A

when calling code receives a thrown exception what are the effects

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
68
Q

when creating a custom exception what should its constructor take as formal parameters

A

1.A string that is a message to display
2.The data that actually caused the problem

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
69
Q

What is the purpose of
Serializable interface?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
70
Q

describe the static method

Objects.requireNonNull(Object obj, String message).

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
71
Q

What is the purpose of the
Error subclass?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
72
Q

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)

A

What are some general rules to follow when deciding whether to use a unchecked exception in Java?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
73
Q

What is thrown in the following code?

throw new IllegalArgumentException(“null parameter received”)

A

A new IllegalArgumentException object with the message “null parameter received.”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
74
Q

What is an
IndexOutOfBoundsException?

A

this is an exception that occurs when we try to access an index that is out of bounds of the operation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
75
Q

Can the FileReader class read lines?

A

No, FileReader cannot read lines by itself.

the Filereader class main use is for reading in chracters.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
76
Q

this is a part of the java.lang package and is commonly used to indicate that invalid actual parameters have been passed to the method or constructor.

A

What is
IllegalArgumentException?

77
Q

we may define these if the provided exceptions do not match with our specific error

A

when might we want to
define our own exception classes

78
Q

How can an invoked code that may throw an exception be documented in JavaDoc?

A

It can be documented using the annotation

@throws

79
Q

Code is most vulnerable via the parameters it is passed, whether in the constructor or any methods, as this could lead to an invalid state of an object or invalid or error-prone operations being carried out.

This helps to prevent such vulnerabilities by ensuring that only valid data is used in the program.

A

Why is
parameter checking
important in defensive programming?

80
Q

What is
parameter checking?

A

This is a technique used in defensive programming that involves checking that received parameters are valid before carrying out any actions with the data.

81
Q

this is a technique that aims to prevent errors from occurring, whether they are caused by:
1. logical errors
2. improper parameters
3. by accident
4. with malicious intent.

A

What is
defensive programming?

82
Q

What is the
Scanner class
used for in Java?

A

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.

83
Q

What happens if an assertion statement evaluates to true?

A

If an assert statement evaluates to true, nothing happens, and execution continues. If it evaluates to false, an AssertionError will be thrown.

84
Q

in order for a resource to make use of this it must implement the AutoCloseable interface that is defined in the java.lang package.

A

for a resource to be able to use the “try with resource” statement what must it implement

85
Q

Should the @throws annotation be included for both checked and unchecked exceptions?

A

As good practice, the @throws annotation should be included with any method that may throw a checked or unchecked exception, although it is not enforced that it is included for either.

86
Q

Why is
error reporting
important in coding?

A

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.

87
Q

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

A

What are two general rules to follow when deciding whether to use a checked exception in Java?

88
Q

When should you use assert statements?

A

these should only be used for consistency and error checking during development and testing, and not in production code.

these are only included in compiled code if the Java compiler has been requested to include them.

89
Q

To accomplish this:

  1. Ensure the class of the object we wish to save implements the Serializable interface.
  2. Create an instance of the ObjectOutputStream class, passing in an OutputStream object.
  3. Call the writeObject() method of the ObjectOutputStream, passing in the object you want to save.
  4. 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();
        }
}
A

What are the 4 steps for saving an object using object serialization? can you write the code?

90
Q

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.

A

What is the purpose of the
Error subclass?

91
Q

What is a
ClassCastException?

A

this is an exception that occurs when we try to cast an object to an incompatible type.

For example, trying to cast an object of type String to type Integer would result in a ClassCastException.

92
Q

in this event The first requirement is that the header of the throwing method includes a throws clause.

A

What is the requirement placed on the invoked code that the compiler checks for when checked exceptions are used?

93
Q

when invoked code detects an error and throws an exception, what are the effects on the invoked code

A

in this event the effects on the invoked code are:
1. exceution stops immediatelly
2. the exception is thrown to the calling code (This is true even if the invoked code should return a value)

94
Q

The natural units to use when performing this are characters and strings.

A

What are the
natural units to use when writing to files?

95
Q

these include:

  1. Solution implemented incorrectly, such as calculating the mean value instead of the median value.
  2. Illegal actions, such as calling a collection with an out-of-bounds index.
  3. Null objects, such as calling a method on a null object and causing a null pointer exception.
A

What are 3 examples of logical errors in a program?

96
Q

What method does BufferedReader class define for reading lines?

A

The BufferedReader class defines a readLine() method for reading lines.

97
Q

to avoid this runtime error we should first check that an object is not null before calling methods on it.

A

How can we code defensively to prevent a
null pointer exception

98
Q

What should be
placed within the try block of a try statement?

A

Within the try block, we would normally place not just the statement that might receive a thrown exception but also any statements that are closely related to that operation/statement.

99
Q

When is an
exception unchecked?

A

this is unchecked if it is a subclass of the RuntimeException class.

100
Q

in terms of a methods documentation this is a set of rules that must be met before calling the method

A

what is a
precondition

101
Q

When can a catch block be omitted in a try statement?

A

If a method will be propagating all exceptions, then the catch block can be omitted completely and only a try and finally block are needed.

102
Q

What is an
Assertion Error?

A

thisis a subclass of Error and belongs to the hierarchy that is regarded as unrecoverable errors.

No handler should be provided in the client for this error.

103
Q

Actions that can be taken here are:

  1. Ensuring that valid parameters are passed to any methods by first checking that a value is not null or empty.
  2. Making an exception impossible to happen, for example by using keyInUse before adding to a set to avoid a DuplicateKeyException.
A

What are 2 actions that can be taken to avoid errors?

104
Q

What happens if
a supertype exception is placed before its subtype in a catch block?

A

If a supertype exception is placed before its subtype in a catch block, then the supertype catch block would be executed first. The compiler will report an error in this case because the later catch blocks will be unreachable.

105
Q

What are the Java packages that provide classes for dealing with input and output?

A

The Java packages that provide classes for dealing with input and output are java.io and java.nio.

106
Q

What is
System.in
in Java?

A

System.in is an object that represents the terminal that the program is currently connected to, also known as standard input.

We can use a Scanner object to read input from the terminal by creating a new Scanner object with System.in as the argument.

Example:

Scanner reader = new Scanner(System.in);

107
Q

What is the
IOException class
in java.io package?

A

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.

108
Q

What are the
two uses of an assertion?

A

The two uses of this are to
1. express what we assume to be true at a given point during runtime
2. and to test for programming errors at runtime.

109
Q

what is a
precondition

A

in terms of a methods documentation this is a set of rules that must be met before calling the method

110
Q

What is the difference between checked and unchecked exceptions?

A

Checked exceptions are checked at compile-time, while unchecked exceptions are not.

Checked exceptions must be declared in the method signature or handled using try-catch, while unchecked exceptions do not need to be handled in this way.

111
Q

What happens when an
unchecked exception is thrown?

A

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.

112
Q

What is the requirement placed on the invoked code that the compiler checks for when checked exceptions are used?

A

in this event The first requirement is that the header of the throwing method includes a throws clause.

113
Q

What is
error recovery?

A

This is a process in programming that involves taking note and action for any errors that may occur, by checking returned values, and implementing recovery where exceptions are in use.

114
Q

in this event the effects on the invoked code are:
1. exceution stops immediatelly
2. the exception is thrown to the calling code (This is true even if the invoked code should return a value)

A

when invoked code detects an error and throws an exception, what are the effects on the invoked code

115
Q

this can be accessed by:
1. calling getMessage() on the exception object.
2. calling toString() on the exception object.
3. viewing the message if the program is caused to terminate

A

How can a calling code access the
message passed to an exception object’s constructor?

116
Q

The two main approaches for this are to notify the user via a GUI or to notify the calling code.

A

What are the two main approaches for
error reporting?

117
Q

thisis a subclass of Error and belongs to the hierarchy that is regarded as unrecoverable errors.

No handler should be provided in the client for this error.

A

What is an
Assertion Error?

118
Q

How can a calling code access the
message passed to an exception object’s constructor?

A

this can be accessed by:
1. calling getMessage() on the exception object.
2. calling toString() on the exception object.
3. viewing the message if the program is caused to terminate

119
Q

What are the three main steps involved in storing data to a file?

A
  1. The file is opened
  2. The data is written
  3. The file is closed
120
Q

What are
protected statements?

A

these are statements that are nested inside a try block.

121
Q

What are 3 examples of logical errors in a program?

A

these include:

  1. Solution implemented incorrectly, such as calculating the mean value instead of the median value.
  2. Illegal actions, such as calling a collection with an out-of-bounds index.
  3. Null objects, such as calling a method on a null object and causing a null pointer exception.
122
Q

What is the syntax and an example of the Try with Resource statement?

A

syntax of this:

try (resource) {
    // code block
} catch {
    // code block
}

example of this:

try (FileWriter writer = new FileWriter(fileName)) {
    // code block
} catch {
    // code block
}
123
Q

What are the overloaded methods for creating a BufferedReader?

A

these include:
1. BufferedReader(Path path) - equivalent to invoking Files.newBufferedReader(path, StandardCharsets.UTF_8)
2. BufferedReader(Path path, Charset cs)

124
Q

in this event the catch block will take over and deal with the exception.

It should be understood that exceptions prevent the normal flow of execution in the calling code. This means that as soon as an exception is thrown, any statements after will not be executed. Instead, the flow will continue into the catch block.

A

What happens when
an exception is thrown in a try statement?

125
Q

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.

A

What is the purpose of
Serializable interface?

126
Q

What are the two categories of exception classes in Java?

A

these include Checked exceptions and unchecked exceptions.

127
Q

What is the preferred method for
error reporting?

A

The preferred method for error reporting is to notify the calling code. This can be achieved by either returning a value that indicates an error has occurred or by throwing an exception.

128
Q

What is the
useDelimiter() method
in the Scanner class used for?

A

This method in the Scanner class is used to set the scanner’s delimiting pattern to a pattern constructed from the specified string.

129
Q

this is an exception that occurs when we try to cast an object to an incompatible type.

For example, trying to cast an object of type String to type Integer would result in a ClassCastException.

A

What is a
ClassCastException?

130
Q

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

A

when deciding whether or not to
code defensively
what are two questions the invoked code should ask?

131
Q

What is
object serialization?

A

This is a process that allows a whole object and its hierarchy to be read or written to a file in a single operation.

It helps to avoid reading and writing fields of an object independently to and from a file, thus saving time and effort.

132
Q

What happens when
an exception is thrown in a try statement?

A

in this event the catch block will take over and deal with the exception.

It should be understood that exceptions prevent the normal flow of execution in the calling code. This means that as soon as an exception is thrown, any statements after will not be executed. Instead, the flow will continue into the catch block.

133
Q

What does the readAllLines() method of the
Files class
return?

A

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.

134
Q

this is when a calling method passes on a thrown exception to another method by including a “throws” clause in its header without actually handling the exception itself.

This is necessary when the calling method is not able to handle the exception and needs to pass it on to a higher level that can handle it appropriately.

A

What is
exception propagation?

135
Q

syntax of this:

try (resource) {
    // code block
} catch {
    // code block
}

example of this:

try (FileWriter writer = new FileWriter(fileName)) {
    // code block
} catch {
    // code block
}
A

What is the syntax and an example of the Try with Resource statement?

136
Q

How can we create a Path object?

A

We can create a Path object by calling the static method “get” of the Paths class and passing a string representing the path as an argument. For example:

Path path = Paths.get(pathString);

137
Q

when calling code receives a thrown exception what are the effects

A

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

138
Q

What are the
natural units to use when writing to files?

A

The natural units to use when performing this are characters and strings.

139
Q

advantages of this include:
1. it will always execute, even if a return statement is present in the try or catch block.
2. If an exception is thrown in the try block and not caught, the finally block will still be executed.

A

What are the
two advantages of using a finally clause?

140
Q

This is a process that allows a whole object and its hierarchy to be read or written to a file in a single operation.

It helps to avoid reading and writing fields of an object independently to and from a file, thus saving time and effort.

A

What is
object serialization?

141
Q

Why is
error recovery
important in file-based input and output?

A

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.

142
Q

What is the role of the Path interface and the Files class?

A

The Path interface and the Files class are part of the java.nio.file package and have a similar role to the File class. They are the modern way to handle files.

143
Q

What is
defensive programming?

A

this is a technique that aims to prevent errors from occurring, whether they are caused by:
1. logical errors
2. improper parameters
3. by accident
4. with malicious intent.

144
Q

these are exceptions that the programmer should expect can fail, such as when writing to a disk and anticipating it could be full.

These exceptions are required to be declared in a method’s throws clause, which means that the programmer is obligated to catch or handle them explicitly.

A

What are checked exceptions in Java?

145
Q

this can be created via a static method of Files named NewBufferedReader().

A

How can a
BufferedReader
be created?

146
Q

in this event we must include a @throws annotation in the javadoc so that it becomes part of the precondition of using the constructor or method

A

if a
method or constructor may throw an exception
what must we provide in the javadoc

147
Q

What is an
exception handler?

A

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.

148
Q

What is a
NullPointerException?

A

this is an exception that occurs when an operation is called on a null object.

149
Q

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

A

describe the static method

Objects.requireNonNull(Object obj, String message).

150
Q

these should only be used for consistency and error checking during development and testing, and not in production code.

these are only included in compiled code if the Java compiler has been requested to include them.

A

When should you use assert statements?

151
Q

What is a try statement, and what is its basic syntax?

A

this statement is a method in Java that can be used to create an exception handler. In its basic syntax, it will use the try and catch keywords.

Try {
    Protect one or more statements
}
Catch(ExceptionType e) {
    Report and/or recover from the exception here
}
152
Q

What is the basic pattern (5 steps) for reading a file. can you write the code aswell.

A

The basic pattern for this is as follows:

  1. Create a Charset object
  2. Create a Path object
  3. Create a BufferedReader object
  4. Read each line using readLine() method until end of file
  5. Close the reader
Charset charset = Charset.forName(StringcharsetName);
Path path = Paths.get(filename)
BufferedReader reader = Files.newBufferedReader(path, charset);
String line = reader.readLine();
While (line != null) {
    // do something with line
    Line = reader.readLine();
}
Reader.close();
153
Q

The potential issues with this is:
1. the possibility that all return values are valid, making it difficult to indicate an error, and the possibility that the error may not be properly understood by the client.
2. the caller could simply ignore the error value or use it improperly in their code.
3. the return value may not make it clear whether the caller or the invoked code is at error

A

What are the potential issues with
returning a value that indicates an error has occurred?

154
Q

What is the requirement placed on the calling code that the compiler will check for when using checked exceptions?

A

in this event the requirement is that the caller must make provisions for dealing with the checked exception, usually by writing an exception handler.

155
Q

What are checked exceptions in Java?

A

these are exceptions that the programmer should expect can fail, such as when writing to a disk and anticipating it could be full.

These exceptions are required to be declared in a method’s throws clause, which means that the programmer is obligated to catch or handle them explicitly.

156
Q

What is the
finally clause in a try statement?

A

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.

157
Q

What is
IllegalArgumentException?

A

this is a part of the java.lang package and is commonly used to indicate that invalid actual parameters have been passed to the method or constructor.

158
Q

in this event the requirement is that the caller must make provisions for dealing with the checked exception, usually by writing an exception handler.

A

What is the requirement placed on the calling code that the compiler will check for when using checked exceptions?

159
Q

when might we want to
define our own exception classes

A

we may define these if the provided exceptions do not match with our specific error

160
Q

The basic pattern for this is as follows:

  1. Create a Charset object
  2. Create a Path object
  3. Create a BufferedReader object
  4. Read each line using readLine() method until end of file
  5. Close the reader
Charset charset = Charset.forName(StringcharsetName);
Path path = Paths.get(filename)
BufferedReader reader = Files.newBufferedReader(path, charset);
String line = reader.readLine();
While (line != null) {
    // do something with line
    Line = reader.readLine();
}
Reader.close();
A

What is the basic pattern (5 steps) for reading a file. can you write the code aswell.

161
Q

Can the throws clause be used for both checked and unchecked exceptions?

A

Yes, the throws clause may be used for both checked and unchecked exceptions.

However, it is recommended to reserve its use only for checked exceptions.

162
Q

what is the syntax that allows a method or constructor to throw multiple exceptions

A

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

163
Q

this is a feature in Java that can be used to automatically close a resource and ensure that this step is not missed.

A

What is the Try with Resource or Automatic Resource Management (ARM)?

164
Q

What is the Try with Resource or Automatic Resource Management (ARM)?

A

this is a feature in Java that can be used to automatically close a resource and ensure that this step is not missed.

165
Q

this is used to find the system’s default character encoding.

A

What is the purpose of System.getProperty(“file.encoding”)?

166
Q

What is the purpose of the
throws clause
in a method header?

A

the purpose of this is to declare that a method may throw one or more checked exceptions.

167
Q

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.

A

What are unchecked exceptions in Java?

168
Q

in this event the options are:
1. catch each exception independently

example:

Try {
   Ref.process();
}
Catch(EOFException e) {
}
Catch(FileNotFoundException e ){
}
  1. 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) {
}
  1. 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
}
A

what are the 3 methods that could be used by a method that may receive multiple exceptions

169
Q

this is unchecked if it is a subclass of the RuntimeException class.

A

When is an
exception unchecked?

170
Q

steps for this include:
1. Creating an exception object using the new keyword.
2. Throwing the exception object using the throw keyword.

A

What are the two
steps of throwing an exception?

171
Q

The key steps involved with this are:

  1. Using a catch block that contains statements to aid in the recovery process.
  2. Trying the failed statement again, which usually means being inside a loop such as a do while.
  3. Implementing a limit on how many times recovery can be attempted, such as a MAX_ATTEMPTS constant.
  4. Logging the error with any state so that it can be investigated later.
A

What are 4 key steps involved in
error recovery?

172
Q

this statement is a method in Java that can be used to create an exception handler. In its basic syntax, it will use the try and catch keywords.

Try {
    Protect one or more statements
}
Catch(ExceptionType e) {
    Report and/or recover from the exception here
}
A

What is a try statement, and what is its basic syntax?

173
Q

This is a process in programming that involves taking note and action for any errors that may occur, by checking returned values, and implementing recovery where exceptions are in use.

A

What is
error recovery?

174
Q

What are 2 actions that can be taken to avoid errors?

A

Actions that can be taken here are:

  1. Ensuring that valid parameters are passed to any methods by first checking that a value is not null or empty.
  2. Making an exception impossible to happen, for example by using keyInUse before adding to a set to avoid a DuplicateKeyException.
175
Q

What are the two main approaches for
error reporting?

A

The two main approaches for this are to notify the user via a GUI or to notify the calling code.

176
Q

How can we code defensively to prevent a
null pointer exception

A

to avoid this runtime error we should first check that an object is not null before calling methods on it.

177
Q

this is an exception that occurs when an operation is called on a null object.

A

What is a
NullPointerException?

178
Q

What are the
two advantages of using a finally clause?

A

advantages of this include:
1. it will always execute, even if a return statement is present in the try or catch block.
2. If an exception is thrown in the try block and not caught, the finally block will still be executed.

179
Q

What are the potential issues with
returning a value that indicates an error has occurred?

A

The potential issues with this is:
1. the possibility that all return values are valid, making it difficult to indicate an error, and the possibility that the error may not be properly understood by the client.
2. the caller could simply ignore the error value or use it improperly in their code.
3. the return value may not make it clear whether the caller or the invoked code is at error

180
Q

What is
exception propagation?

A

this is when a calling method passes on a thrown exception to another method by including a “throws” clause in its header without actually handling the exception itself.

This is necessary when the calling method is not able to handle the exception and needs to pass it on to a higher level that can handle it appropriately.

181
Q

in terms of error recovery and discovery what is an important point to keep in mind about exceptions?

A

The place of discovery and place of recovery (if possible) will be distinct from each other.

The place of discovery will be inside the invoked code, and the place of recovery will be in the calling code.

If recovery were possible at the time of discovery, then there would be no need to signal an error.

182
Q

What are some general rules to follow when deciding whether to use a unchecked exception in Java?

A

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)

183
Q

What is
error avoidance?

A

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.

184
Q

What package contains Charsets?

A

these may be found in the java.nio.charset package.

185
Q

The two uses of this are to
1. express what we assume to be true at a given point during runtime
2. and to test for programming errors at runtime.

A

What are the
two uses of an assertion?

186
Q

Logical errors cannot be spotted by the compiler unlike syntactical errors and will only show up at some point during runtime.

A

Why is it often harder to find logical errors in a program?

187
Q

When is exception propagation commonly used?

A

Exception propagation is commonly used in two scenarios:

  1. When the code cannot itself deal with the exception, perhaps because it can only be dealt with at a higher level
  2. When object creation fails in constructors, and the constructor cannot itself recover
188
Q

if a
method or constructor may throw an exception
what must we provide in the javadoc

A

in this event we must include a @throws annotation in the javadoc so that it becomes part of the precondition of using the constructor or method

189
Q

Why is
parameter checking
important in defensive programming?

A

Code is most vulnerable via the parameters it is passed, whether in the constructor or any methods, as this could lead to an invalid state of an object or invalid or error-prone operations being carried out.

This helps to prevent such vulnerabilities by ensuring that only valid data is used in the program.