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
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?**
26
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?**
27
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?
28
What is the purpose of **System.getProperty("file.encoding")?**
this is used to find the system's default character encoding.
29
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.
30
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?
31
What is the general pattern for writing to a file in Java? describe general steps and write the code
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(); ```
32
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.
33
What are 4 key steps involved in **error recovery?**
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.
34
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?
35
these are exceptions that the compiler enforces few rules on their use, and they are not checked by the compiler.
What are **unchecked exceptions?**
36
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.
37
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
38
these are statements that are nested inside a try block.
What are **protected statements?**
39
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
40
[Chapter 14 glossary quiz](https://learn2.open.ac.uk/mod/quiz/view.php?id=2014947)
ignore
41
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?
42
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?
43
What is an **assertion?**
An assertion is a statement or fact that should evaluate to true in normal execution at runtime.
44
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?**
45
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(); ```
What is the general pattern for writing to a file in Java? describe general steps and write the code
46
What is the purpose of the **Exception subclass?**
this is usually used for errors that the programmer may have control over.
47
subclasses of this include Error and Exception.
What are the two subclasses of **Throwable?**
48
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.
49
An assertion is a statement or fact that should evaluate to true in normal execution at runtime.
What is an **assertion?**
50
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`. 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
51
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?
52
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`. 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?
53
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?
54
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.
55
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?
56
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
57
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.
58
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**
59
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.
60
The natural units to use when performing this are characters and lines.
What are the **natural units to use when reading from files?**
61
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?
62
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.
63
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
64
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.
65
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 ){ } ``` 2. 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) { } ``` 3. 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 } ```
66
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?
67
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
68
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
69
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.
70
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
71
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.
72
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?
73
What is thrown in the following code? `throw new IllegalArgumentException(“null parameter received”)`
A new IllegalArgumentException object with the message "null parameter received."
74
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.
75
Can the FileReader class read lines?
No, FileReader cannot read lines by itself. the Filereader class main use is for reading in chracters.
76
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.
What is **IllegalArgumentException?**
77
we may define these if the provided exceptions do not match with our specific error
when might we want to **define our own exception classes**
78
How can an invoked code that may throw an exception be documented in JavaDoc?
It can be documented using the annotation `@throws`
79
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.
Why is **parameter checking** important in defensive programming?
80
What is **parameter checking?**
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
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.
What is **defensive programming?**
82
What is the **Scanner class** used for in Java?
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
What happens if an assertion statement evaluates to true?
If an assert statement evaluates to true, nothing happens, and execution continues. If it evaluates to false, an AssertionError will be thrown.
84
in order for a resource to make use of this it must implement the AutoCloseable interface that is defined in the java.lang package.
for a resource to be able to use the "try with resource" statement what must it implement
85
Should the @throws annotation be included for both checked and unchecked exceptions?
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
Why is **error reporting** important in coding?
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
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
What are two general rules to follow when **deciding whether to use a checked exception** in Java?
88
When should you use assert statements?
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
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(); } } ```
What are the 4 steps for saving an object using object serialization? can you write the code?
90
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.
What is the purpose of the **Error subclass?**
91
What is a **ClassCastException?**
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
in this event The first requirement is that the header of the throwing method includes a throws clause.
What is the requirement placed on the invoked code that the compiler checks for when **checked exceptions are used?**
93
when invoked code detects an error and throws an exception, what are the effects on the invoked code
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
The natural units to use when performing this are characters and strings.
What are the **natural units to use when writing to files?**
95
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.
What are 3 examples of logical errors in a program?
96
What method does BufferedReader class define for reading lines?
The BufferedReader class defines a readLine() method for reading lines.
97
to avoid this runtime error we should first check that an object is not null before calling methods on it.
How can we code defensively to prevent a **null pointer exception**
98
What should be **placed within the try block of a try statement?**
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
When is an **exception unchecked?**
this is unchecked if it is a subclass of the RuntimeException class.
100
in terms of a methods documentation this is a set of rules that must be met before calling the method
what is a **precondition**
101
When can a catch block be omitted in a try statement?
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
What is an **Assertion Error?**
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
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.
What are 2 actions that can be taken to avoid errors?
104
What happens if **a supertype exception is placed before its subtype in a catch block?**
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
What are the Java packages that provide classes for dealing with input and output?
The Java packages that provide classes for dealing with input and output are java.io and java.nio.
106
What is **System.in** in Java?
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
What is the **IOException class** in java.io package?
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
What are the **two uses of an assertion?**
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
what is a **precondition**
in terms of a methods documentation this is a set of rules that must be met before calling the method
110
What is the difference between checked and unchecked exceptions?
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
What happens when an **unchecked exception is thrown?**
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
What is the requirement placed on the invoked code that the compiler checks for when **checked exceptions are used?**
in this event The first requirement is that the header of the throwing method includes a throws clause.
113
What is **error recovery?**
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
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)
when invoked code detects an error and throws an exception, what are the effects on the invoked code
115
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
How can a calling code access the **message passed to an exception object's constructor?**
116
The two main approaches for this are to notify the user via a GUI or to notify the calling code.
What are the two main approaches for **error reporting?**
117
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.
What is an **Assertion Error?**
118
How can a calling code access the **message passed to an exception object's constructor?**
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
What are the three main steps involved in storing data to a file?
1. The file is opened 2. The data is written 3. The file is closed
120
What are **protected statements?**
these are statements that are nested inside a try block.
121
What are 3 examples of logical errors in a program?
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
What is the syntax and an example of the Try with Resource statement?
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
What are the overloaded methods for creating a BufferedReader?
these include: 1. BufferedReader(Path path) - equivalent to invoking Files.newBufferedReader(path, StandardCharsets.UTF_8) 2. BufferedReader(Path path, Charset cs)
124
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.
What happens when **an exception is thrown in a try statement?**
125
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.
What is the purpose of **Serializable interface?**
126
What are the **two categories of exception classes** in Java?
these include Checked exceptions and unchecked exceptions.
127
What is the preferred method for **error reporting?**
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
What is the **useDelimiter() method** in the Scanner class used for?
This method in the Scanner class is used to set the scanner's delimiting pattern to a pattern constructed from the specified string.
129
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.
What is a **ClassCastException?**
130
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
when deciding whether or not to **code defensively** what are two questions the invoked code should ask?
131
What is **object serialization?**
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
What happens when **an exception is thrown in a try statement?**
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
What does the readAllLines() method of the **Files class** return?
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
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.
What is **exception propagation?**
135
syntax of this: ``` try (resource) { // code block } catch { // code block } ``` example of this: ``` try (FileWriter writer = new FileWriter(fileName)) { // code block } catch { // code block } ```
What is the syntax and an example of the Try with Resource statement?
136
How can we create a Path object?
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
when **calling code receives a thrown exception** what are the effects
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
What are the **natural units to use when writing to files?**
The natural units to use when performing this are characters and strings.
139
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.
What are the **two advantages of using a finally clause?**
140
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.
What is **object serialization?**
141
Why is **error recovery** important in file-based input and output?
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
What is the role of the Path interface and the Files class?
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
What is **defensive programming?**
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
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.
What are **checked exceptions** in Java?
145
this can be created via a static method of Files named NewBufferedReader().
How can a **BufferedReader** be created?
146
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
if a **method or constructor may throw an exception** what must we provide in the javadoc
147
What is an **exception handler?**
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
What is a **NullPointerException?**
this is an exception that occurs when an operation is called on a null object.
149
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
describe the static method `Objects.requireNonNull(Object obj, String message).`
150
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.
When should you use assert statements?
151
What is a try statement, and what is its basic syntax?
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
What is the basic pattern (5 steps) for reading a file. can you write the code aswell.
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(String charsetName); 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
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
What are the potential issues with **returning a value that indicates an error has occurred?**
154
What is the requirement placed on the calling code that the compiler will check for when using checked exceptions?
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
What are **checked exceptions** in Java?
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
What is the **finally clause in a try statement?**
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
What is **IllegalArgumentException?**
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
in this event the requirement is that the caller must make provisions for dealing with the checked exception, usually by writing an exception handler.
What is the requirement placed on the calling code that the compiler will check for when using checked exceptions?
159
when might we want to **define our own exception classes**
we may define these if the provided exceptions do not match with our specific error
160
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(String charsetName); 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(); ```
What is the basic pattern (5 steps) for reading a file. can you write the code aswell.
161
Can the throws clause be used for both checked and unchecked exceptions?
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
what is the syntax that allows a method or constructor to throw multiple exceptions
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
this is a feature in Java that can be used to automatically close a resource and ensure that this step is not missed.
What is the Try with Resource or Automatic Resource Management (ARM)?
164
What is the Try with Resource or Automatic Resource Management (ARM)?
this is a feature in Java that can be used to automatically close a resource and ensure that this step is not missed.
165
this is used to find the system's default character encoding.
What is the purpose of **System.getProperty("file.encoding")?**
166
What is the purpose of the **throws clause** in a method header?
the purpose of this is to declare that a method may throw one or more checked exceptions.
167
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.
What are **unchecked exceptions** in Java?
168
in this event the options are: 1. catch each exception independently example: ``` Try { Ref.process(); } Catch(EOFException e) { } Catch(FileNotFoundException e ){ } ``` 2. 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) { } ``` 3. 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 } ```
what are the 3 methods that could be used by a method that may receive multiple exceptions
169
this is unchecked if it is a subclass of the RuntimeException class.
When is an **exception unchecked?**
170
steps for this include: 1. Creating an exception object using the new keyword. 2. Throwing the exception object using the throw keyword.
What are the two **steps of throwing an exception?**
171
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.
What are 4 key steps involved in **error recovery?**
172
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 } ```
What is a try statement, and what is its basic syntax?
173
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.
What is **error recovery?**
174
What are 2 actions that can be taken to avoid errors?
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
What are the two main approaches for **error reporting?**
The two main approaches for this are to notify the user via a GUI or to notify the calling code.
176
How can we code defensively to prevent a **null pointer exception**
to avoid this runtime error we should first check that an object is not null before calling methods on it.
177
this is an exception that occurs when an operation is called on a null object.
What is a **NullPointerException?**
178
What are the **two advantages of using a finally clause?**
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
What are the potential issues with **returning a value that indicates an error has occurred?**
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
What is **exception propagation?**
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
in terms of error recovery and discovery what is an important point to keep in mind about exceptions?
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
What are some general rules to follow when deciding whether to use a unchecked exception in Java?
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
What is **error avoidance?**
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
What package contains **Charsets?**
these may be found in the java.nio.charset package.
185
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.
What are the **two uses of an assertion?**
186
Logical errors cannot be spotted by the compiler unlike syntactical errors and will only show up at some point during runtime.
Why is it often harder to find logical errors in a program?
187
When is exception propagation commonly used?
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
if a **method or constructor may throw an exception** what must we provide in the javadoc
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
Why is **parameter checking** important in defensive programming?
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.