4.1.1.9 - Exceptions and defensive input (Java)

4.1.1.9 - Exceptions and defensive input (Java)

Recognise Java exceptions, handle a specific failure, and combine conversion checks with validation so input can recover safely.

Java route status: incomplete: runnable support pending. Code responses are written Java with no execution control.

Exceptional conditions

An exception signals that an operation could not complete normally and transfers control to a matching handler if one exists.

Exception

An object representing an exceptional condition raised during program execution; normal flow is interrupted until a suitable handler is found.

Examples include converting "apple" to an integer (NumberFormatException), accessing an array outside its bounds (ArrayIndexOutOfBoundsException) and dividing an integer by zero (ArithmeticException). A syntax error prevents compilation and is not a runtime exception that a catch block repairs. A logical error, such as an incorrect discount threshold, may produce wrong results without raising any exception.

Java
int amount = Integer.parseInt("apple");
System.out.println("Accepted " + amount);

The conversion fails, so the assignment does not complete and the print statement is not reached. An uncaught exception propagates out through calls and can end the program. Do not claim that all bad data raise exceptions: Integer.parseInt("-4") succeeds, even if a booking cannot have a negative quantity. Validation must enforce such business rules separately. Floating-point division by zero is also different from integer division: Java can produce infinity or NaN rather than ArithmeticException.

Handling and reporting errors

A try block contains an operation that may fail, and a catch block supplies the recovery for a specified exception type.

Java
String text = "six";
try {
    int quantity = Integer.parseInt(text);
    System.out.println("Quantity " + quantity);
} catch (NumberFormatException error) {
    System.out.println("Enter a whole number");
}
System.out.println("Finished attempt");

The conversion raises NumberFormatException, so the rest of the try block is skipped. The matching handler prints the useful message, then flow continues after the handled try/catch and prints Finished attempt. With text "6", the handler is skipped and the two lines are Quantity 6 and Finished attempt. A catch for an unrelated exception would not handle this failure.

Keep the protected operation and handler specific. Catching every Exception and silently ignoring it can hide programming defects and leave state invalid. The handler should report what the user can fix or deliberately propagate a failure it cannot recover from. If several catches are used, put a more specific type before a broader type that includes it.

An optional finally block ordinarily runs after a try/catch whether the operation succeeds or throws. It is useful for cleanup, not for declaring that a failed operation succeeded. This does not promise execution if the process is forcibly terminated. The examples need only try/catch; file-handling lessons explain resource cleanup in context.

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account