[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.

What are Java Exceptions REQUIRED:

References:

Types of Exception REQUIRED:

References:

Handle exception in Java REQUIRED:

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:

Custom an exception REQUIRED:

References:

Chained Exceptions in Java REQUIRED:

References:

Quizzes:

  1. What is an exception in Java? How many exception types are in Java? What do you understand about throwables in Java?
  2. What are the differences between checked and unchecked exceptions? Pros and Cons of checked and unchecked exceptions?
  3. What are the differences between error and exception?
  4. What is NullPointerException?
  5. What is exception propagation in Java?
  6. What are chained exceptions in Java?
  7. What is the difference between the throw and throws keywords?
  8. How to handle exceptions in Java? Can you catch and handle Multiple Exceptions in Java?
  9. What do you understand about unreachable catch block errors?
  10. Explain the try catch finally block and try with resource. When do we use it?
  11. Can the catch block be empty? Can we miss the catch block?
  12. Is it OK to write? What happens if the error occurs in try block?
try {
   ...
} finally {
   ...
}
  1. 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:

  1. Write a Java program that throws a checked exception and catches it using a try-catch block.
  2. Write a Java program that throws an unchecked exception and catches it using a try-catch block.
  3. 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.
  1. 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);
  }
}
  1. Create a custom class that follows the Closeable or AutoCloseable interface. This class should have a method named divide, which takes two parameters, x and y, and calculates the result of x/y. Afterward, write a program that retrieves values for x and y from the user input. Utilize the try-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 the ArithmeticException when calculating, should display a clear error message to the user if the exception occurs.