[Draft] Training Guide ‐ Java Exception - vinhtbkit/bkit-kb GitHub Wiki
When executing a Java program an unwanted or unexpected event will occur.
Target: the trainee will know how to handle, and the mechanism of exception in Java.
Expected Duration: maximum 24 hours of training and working on exercises.
Qualification criteria:
- Exception Hierarchy.
- Types of exceptions in Java.
- Difference between Error and Exception.
- Difference between Checked and Unchecked exceptions.
- Know how to handle an exception.
REQUIRED
:
What are Java Exceptions References:
- https://www.geeksforgeeks.org/exceptions-in-java/?ref=lbp
- General: https://www.baeldung.com/java-exceptions
- Oracle docs: https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html
REQUIRED
:
Types of Exception References:
- https://www.geeksforgeeks.org/types-of-exception-in-java-with-examples/?ref=lbp
- https://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/?ref=lbp
REQUIRED
:
Handle exception in Java Some questions for this session:
- How to handle an exception?
- When we should rethrow and when should handle an exception?
- How to log an exception properly?
References:
- https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html
- https://www.geeksforgeeks.org/throw-throws-java/?ref=lbp
- https://www.geeksforgeeks.org/exception-handling-with-method-overriding-in-java/?ref=lbp
- https://github.com/vinhtbkit/bkit-kb/wiki/%5BDraft%5D-Best-practices-for-handling-exceptions-in-Java
REQUIRED
:
Custom an exception References:
- https://www.geeksforgeeks.org/user-defined-custom-exception-in-java/
- https://www.baeldung.com/java-new-custom-exception
REQUIRED
:
Chained Exceptions in Java References:
Quizzes:
- What is an exception in Java? How many exception types are in Java? What do you understand about throwables in Java?
- What are the differences between checked and unchecked exceptions? Pros and Cons of checked and unchecked exceptions?
- What are the differences between error and exception?
- What is NullPointerException?
- What is exception propagation in Java?
- What are chained exceptions in Java?
- What is the difference between the
throw
andthrows
keywords? - How to handle exceptions in Java? Can you catch and handle Multiple Exceptions in Java?
- What do you understand about unreachable catch block errors?
- Explain the
try catch finally
block andtry with resource
. When do we use it? - Can the
catch
block be empty? Can we miss thecatch
block? - Is it OK to write? What happens if the error occurs in
try
block?
try {
...
} finally {
...
}
- Give the custom closeable class below:
public class CustomCloseable implements AutoCloseable {
@Override
public void close() throws IOException {
throw new IOException("Exception from closeable");
}
}
public class ExceptionExample {
public static void main(String[] args) throws Exception {
try {
tryCatchFinally();
} catch (Exception ex) {
// What is an exception thrown here?
System.out.println(ex.getMessage());
}
try {
tryWithResource();
} catch (Exception ex) {
// What is an exception thrown here? How can we retrieve an IOException that is thrown by customCloseable.close()? What exception type of it this case?
System.out.println(ex.getMessage());
}
}
public static void tryCatchFinally() throws IOException {
CustomCloseable customCloseable = new CustomCloseable();
try {
System.out.println(customCloseable);
throw new IllegalArgumentException("exception in try block");
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("exception in catch block", e);
} finally {
customCloseable.close();
}
}
public static void tryWithResource() throws IOException {
try (CustomCloseable customCloseable = new CustomCloseable()) {
System.out.println(customCloseable);
throw new IllegalArgumentException("exception in try block");
} catch (IllegalArgumentException exception) {
throw new IllegalArgumentException("exception in catch block", exception);
} catch (IOException e) {
throw new IOException(e);
}
}
}
Assignments:
Requires:
Java 11+, using the command line to compile and execute.
Exercise:
- Write a Java program that throws a checked exception and catches it using a try-catch block.
- Write a Java program that throws an unchecked exception and catches it using a try-catch block.
- Write a small program to calculate the sum of array integer numbers inputted from the command line. Ex: input: 1,2,3,4,5
- You need to split the string by
,
to get an array integer number. The input may include strings, Ex: 1, two, three,4,5- You should write a validate method that tries to parse a string to an integer and handle the exception thrown, catch the exception, and display invalid numbers to the user.
- Give the following code, and decide to handle or choose an exception to throw:
public class DataProcessor {
public static void main(String[] args) {
DataProcessor dataProcessor = new DataProcessor();
String filename = "filename.txt";
try {
dataProcessor.processData(filename);
} catch (e) {
// Do I need to catch and handle an exception at this level?
}
}
public void processData(String filename) {
try {
// Step 1: Read data from an external source
String rawData = readData(filename);
// Step 2: Process the data
String processedData = processRawData(rawData);
// Step 3: Save the processed data
saveDataToANewFile(processedData, filename);
} catch (e) {
// Do I need to catch and handle an exception at this level?
}
}
private String readData(String filename) {
// Simulate reading data from an external source
try {
// read data by filename
return "data";
} catch (IOException e) {
// For simplicity, let's assume an IOException might occur during reading
// Should I re-throw or handling the IOException?
}
}
private String processRawData(String rawData) {
// Let's assume that we can not process if the parameter is null or empty
if (rawData == null || rawData.isEmpty()) {
// Should I throw an exception or return something?
}
// Simulate data processing
return "Processed: " + rawData;
}
private void saveDataToANewFile(String processedData, String filename) {
final String copyFileName = "copy_" + filename;
try {
// Simulate saving processed data
} catch (IOException e) {
// Let's assume an IOException might occur during reading
// Should I re-throw or handling the IOException?
}
}
}
class ProcessingException extends Exception {
public ProcessingException(String message) {
super(message);
}
public ProcessingException(String message, Throwable cause) {
super(message, cause);
}
}
- Create a custom class that follows the
Closeable
orAutoCloseable
interface. This class should have a method nameddivide
, which takes two parameters,x
andy
, and calculates the result ofx/y
. Afterward, write a program that retrieves values for x and y from the user input. Utilize thetry-with-resources
statement to instantiate an object of your custom class and invoke the divide method to obtain the result. Finally, display the result to the user. Don't forget to catch and handle theArithmeticException
when calculating, should display a clear error message to the user if the exception occurs.